Skip to main content
 首页 » 编程设计

python之捕获来自应用程序的完整请求

2025年05月04日7JustinYoung

我正在编写一个 Python 应用程序,它查询多个网络服务器,每个服务器每分钟一次。应用程序运行良好几分钟,然后所有服务器开始响应以下错误:

The following cURL error occurred: The requested URL returned error: 400 Bad Request

发生这种情况时,我看到我的传出带宽 Hook 和两个 CPU 内核都在 80% 以上(这台机器上的负载非常轻)。但是,内存使用不会受到显着影响。

有没有办法捕获从特定应用程序发送的所有请求的完整请求?或者,在 Python 中,我可以捕获完整的请求,然后将其输出回来用于调试目的吗?这是查询服务器的代码部分:

output = cStringIO.StringIO() 
c = pycurl.Curl() 
c.setopt(c.URL, url) 
c.setopt(c.USERAGENT, 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:17.0) Gecko/20100101 Firefox/17.0') 
c.setopt(c.WRITEFUNCTION, output.write) 
c.setopt(c.CONNECTTIMEOUT, 10)  
c.setopt(c.TIMEOUT, 15)  
c.setopt(c.FAILONERROR, True) 
c.setopt(c.NOSIGNAL, 1) 
 
try: 
    c.perform() 
    toReturn = output.getvalue() 
    output.close() 
    return toReturn 
 
except pycurl.error, error: 
    errno, errstr = error 
    print 'The following cURL error occurred: ', errstr 

该机器是双核 2.0 GHz Intel 机箱,配备 6 GiB RAM,运行 Kubuntu 12.10 和 Python 2.7。一切都在 VIM 中编码,因此没有乱七八糟的虚假 IDE 代码。

请您参考如下方法:

Is there any way to capture the entire request for all requests sent from a particular application?

捕获和监控所有传入/传出流量(包括从您的应用程序发送的请求)的最简单方法是使用 wireshark

Alternatively, in Python can I capture the full request and then output it back for debugging purposes?

您可以添加以下调试选项,以便 curl 打印有关请求的一些有用信息:

c.setopt(pycurl.VERBOSE, 1)