import pcap # 安装的是pypcap,本博客有安装方法,不过也比较乱,试试吧。
import dpkt
import socket
import datetime
def sniffer(str):
pc = pcap.pcap()
for timestamp, buf in pc:
eth = dpkt.ethernet.Ethernet(buf)
if not isinstance(eth.data, dpkt.ip.IP):
print('Non IP Packet type not supported %s\n' % eth.data.__class__.__name__)
continue
ip = eth.data
if isinstance(ip.data, dpkt.tcp.TCP):
tcp = ip.data
try:
request = dpkt.http.Request(tcp.data)
except (dpkt.dpkt.NeedData, dpkt.dpkt.UnpackError):
continue
print('HTTP request: %s\n' % repr(request))
if request.headers['host'] == str: # 自行替换需要抓的网站。
print(request)
# print('type:', type(request))
host = request.headers['host']
connection = request.headers['connection']
accept = request.headers['accept']
user_agent = request.headers['user-agent']
accept_encoding = request.headers['accept-encoding']
accept_language = request.headers['accept-language']
cookie = request.headers['cookie']
return request
break
request = sniffer('www.******.net')
print('---------')
print(request.headers['host'])
这个代码是抓取一个网站请求的request信息。