windows下:
winpcap下载
http://www.pc6.com/softview/SoftView_17547.html#download
pypcap-1.1.3-py2.7-win32.egg
http://download.csdn.net/download/lone_wolf_pqj/8855665
使用方法:
安装winpcap后,执行:easy_install pypcap-1.1.3-py2.7-win32.egg 即可安装pcap,不需要编译源码(编译源码需要安装vc9.0 for python,并下载pypcap源码和wpdpack)。
使用easy_install需要安装ez_setup:pip install es_setup
参考:
Python黑客编程基础3网络数据监听和过滤
https://zhuanlan.zhihu.com/p/21443605
例子:
import pcap
import dpkt
host='host'
urlex='urlex'
pc=pcap.pcap()
pc.setfilter('tcp port 80')
for ptime,pdata in pc:
host = ""
urlex = ""
p=dpkt.ethernet.Ethernet(pdata)
if p.data.__class__.__name__=='IP':
ip='%d.%d.%d.%d'%tuple(map(ord,list(p.data.dst)))
if p.data.data.__class__.__name__=='TCP':
if p.data.data.dport==80:
#print p.data.data.data
sStr1 = p.data.data.data
# print "==============data=================="
# print sStr1
# print "===================================="
sStr2 = 'Host: '
sStr3 = 'Connection'
sStr4 = 'GET /'
sStr5 = ' HTTP/1.1'
nPos = sStr1.find(sStr3)
nPosa = sStr1.find(sStr5)
if sStr1.find(sStr2) >= 0:
for n in range(sStr1.find(sStr2)+6,nPos-1):
host=sStr1[sStr1.find(sStr2)+6:n]
# print "n:" + n.__str__() + " " + "host" + host
if (sStr1.find(sStr4) >= 0):
for n in range(sStr1.find(sStr4)+4,nPosa+1):
urlex=sStr1[sStr1.find(sStr4)+4:n]
# print "n:" + n.__str__() + " " + "urlex" + urlex
result=host+urlex
if result.__len__() > 0:
print "==============result=================="
print result
print "======================================"
例子:
import pcap
import dpkt
import time
def captData():
pc = pcap.pcap()
pc.setfilter('tcp port 80')
for ptime, pdata in pc:
anlyCap(ptime, pdata);
def anlyCap(ptime, pdata):
content = "baidu.com";
p = dpkt.ethernet.Ethernet(pdata)
ipData = p.data
if ipData.__class__.__name__ == 'IP':
sip = '%d.%d.%d.%d' % tuple(map(ord, list(ipData.src)))
dip = '%d.%d.%d.%d' % tuple(map(ord, list(ipData.dst)))
tcpData = ipData.data
appData = tcpData.data
if appData.find(content) <> -1:
print "find: " + content
x = time.localtime(ptime)
ptimeS = time.strftime('%Y-%m-%d %H:%M:%S', x)
sport = tcpData.sport
dport = tcpData.dport
sportS = str(sport)
dportS = str(dport)
if tcpData.__class__.__name__ == 'TCP':
if tcpData.dport == 80: # HTTP
print "========== " + ptimeS + " " + sip + ":" + sportS + " --> " + dip + ":" + dportS + " HTTP ==========";
print appData
elif tcpData.dport == 443: # HTTPS
print "========== " + ptimeS + " " + sip + ":" + sportS + " --> " + dip + ":" + dportS + " HTTPS ==========";
print appData
elif tcpData.dport == 25: # SMTP
print "========== " + ptimeS + " " + sip + ":" + sportS + " --> " + dip + ":" + dportS + " SMTP ==========";
print appData
else:
print "========== " + ptimeS + " " + sip + ":" + sportS + " --> " + dip + ":" + dportS + " Other ==========";
print appData
elif tcpData.__class__.__name__ == 'UDP':
print "========== " + ptimeS + " " + sip + ":" + sportS + " --> " + dip + ":" + dportS + " UDP ==========";
print appData
captData()