我使用scapy来嗅探一些数据包,我得到一些HTTP响应数据包,这是我无法解析的字节。例如:
b'HTTP/1.1 200 OK\r\nDate: Thu, 07 Dec 2017 02:44:18 GMT\r\nServer:Apache/2.4.18 (Ubuntu)\r\nLast-Modified: Tue, 14 Nov 2017 05:51:36 GMT\r\nETag: "2c39-55deafadf0ac0-gzip"\r\nAccept-Ranges: bytes\r\nVary: Accept-Encoding\r\nContent-Encoding: gzip\r\nContent-Length: 3186\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n\x1f\x8b'
有没有办法获取此字节数组的内容部分,以便我可以使用gzip库进行解码?我不想使用request
来获取HTTP响应,因为我只想处理我的原始数据包。
答案 0 :(得分:2)
没有内置方法来解析像这样的原始HTTP响应并正确处理压缩。我会使用urllib3
:
import urllib3
from io import BytesIO
from http.client import HTTPResponse
class BytesIOSocket:
def __init__(self, content):
self.handle = BytesIO(content)
def makefile(self, mode):
return self.handle
def response_from_bytes(data):
sock = BytesIOSocket(data)
response = HTTPResponse(sock)
response.begin()
return urllib3.HTTPResponse.from_httplib(response)
if __name__ == '__main__':
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('httpbin.org', 80))
sock.send(b'GET /gzip HTTP/1.1\r\nHost: httpbin.org\r\n\r\n')
raw_response = sock.recv(8192)
response = response_from_bytes(raw_response)
print(response.headers)
print(response.data)
答案 1 :(得分:0)
您可以使用
提取字节的值部分response_bytes.decode('utf-8')
然后,您可以使用Beautiful Soup解析返回的信息,无论您想要什么部分。