① pcap文件怎么解 python
字段显示的都是十六进制,其中的数据部分和wireshark打开,显示的十六进制窗口一样。
其实如果程序想到得到某一个或某几个字节的十进制数,用struct还是很容易转换的!
② 如何利用libpcap和Python嗅探数据包
你的python没有安装好。.py文件没有被注册成正确的python关联。你选择“始终使用”这个选项吧。 感觉怪怪的。通常我们安装都会顺利。 另外python所在的目录一定要放到系统环境变量的path里
③ python3.2 下的抓包库。。无论是pypcap还是scapy。貌似都没有py3的版本。。跪求一个可以python3用
有一个py3kcap是pycap的封装版本,可以用于python3版本。
给你一个使用的示例代码:
#!/usr/bin/env python3.2
import ctypes,sys
from ctypes.util import find_library
#pcap = ctypes.cdll.LoadLibrary("libpcap.so")
pcap = None
if(find_library("libpcap") == None):
print("We are here!")
pcap = ctypes.cdll.LoadLibrary("libpcap.so")
else:
pcap = ctypes.cdll.LoadLibrary(find_library("libpcap"))
# required so we can access bpf_program->bf_insns
"""
struct bpf_program {
u_int bf_len;
struct bpf_insn *bf_insns;}
"""
class bpf_program(ctypes.Structure):
_fields_ = [("bf_len", ctypes.c_int),("bf_insns", ctypes.c_void_p)]
class sockaddr(ctypes.Structure):
_fields_=[("sa_family",ctypes.c_uint16),("sa_data",ctypes.c_char*14)]
class pcap_pkthdr(ctypes.Structure):
_fields_ = [("tv_sec", ctypes.c_long), ("tv_usec", ctypes.c_long), ("caplen", ctypes.c_uint), ("len", ctypes.c_uint)]
pkthdr = pcap_pkthdr()
program = bpf_program()
# prepare args
snaplen = ctypes.c_int(1500)
#buf = ctypes.c_char_p(filter)
optimize = ctypes.c_int(1)
mask = ctypes.c_uint()
net = ctypes.c_uint()
to_ms = ctypes.c_int(100000)
promisc = ctypes.c_int(1)
filter = bytes(str("port 80"), 'ascii')
buf = ctypes.c_char_p(filter)
errbuf = ctypes.create_string_buffer(256)
pcap_close = pcap.pcap_close
pcap_lookupdev = pcap.pcap_lookupdev
pcap_lookupdev.restype = ctypes.c_char_p
#pcap_lookupnet(dev, &net, &mask, errbuf)
pcap_lookupnet = pcap.pcap_lookupnet
#pcap_t *pcap_open_live(const char *device, int snaplen,int promisc, int to_ms,
#char *errbuf
pcap_open_live = pcap.pcap_open_live
#int pcap_compile(pcap_t *p, struct bpf_program *fp,const char *str, int optimize,
#bpf_u_int32 netmask)
pcap_compile = pcap.pcap_compile
#int pcap_setfilter(pcap_t *p, struct bpf_program *fp);
pcap_setfilter = pcap.pcap_setfilter
#const u_char *pcap_next(pcap_t *p, struct pcap_pkthdr *h);
pcap_next = pcap.pcap_next
# int pcap_compile_nopcap(int snaplen, int linktype, struct bpf_program *program,
# const char *buf, int optimize, bpf_u_int32 mask);
pcap_geterr = pcap.pcap_geterr
pcap_geterr.restype = ctypes.c_char_p
#check for default lookup device
dev = pcap_lookupdev(errbuf)
#override it for now ..
dev = bytes(str("wlan0"), 'ascii')
if(dev):
print("{0} is the default interface".format(dev))
else:
print("Was not able to find default interface")
if(pcap_lookupnet(dev,ctypes.byref(net),ctypes.byref(mask),errbuf) == -1):
print("Error could not get netmask for device {0}".format(errbuf))
sys.exit(0)
else:
print("Got Required netmask")
handle = pcap_open_live(dev,snaplen,promisc,to_ms,errbuf)
if(handle is False):
print("Error unable to open session : {0}".format(errbuf.value))
sys.exit(0)
else:
print("Pcap open live worked!")
if(pcap_compile(handle,ctypes.byref(program),buf,optimize,mask) == -1):
# this requires we call pcap_geterr() to get the error
err = pcap_geterr(handle)
print("Error could not compile bpf filter because {0}".format(err))
else:
print("Filter Compiled!")
if(pcap_setfilter(handle,ctypes.byref(program)) == -1):
print("Error couldn't install filter {0}".format(errbuf.value))
sys.exit(0)
else:
print("Filter installed!")
if(pcap_next(handle,ctypes.byref(pkthdr)) == -1):
err = pcap_geterr(handle)
print("ERROR pcap_next: {0}".format(err))
print("Got {0} bytes of data".format(pkthdr.len))
pcap_close(handle)
④ 使用pcap库写的抓包程序 抓到数据包之后进行修改在发送给服务器
一般来说,网卡是收不到自己发送出去的数据包的一份拷贝的。
建议楼主研读《TCP IP详解卷一:协议》《TCP IP详解卷二:实现》。
建议使用wireshark这种比较权威的抓包软件抓包并且解析一下你发送和接收的包的每个字节是否如你所愿。
用 pcap_sendpacket 发送的包是应该要包含原始的以太网头部的吧,你的包貌似只有 IP 头,没有以太网的头部哦。
⑤ python2.7 能安装libpcap(抓包)库吗
你好:
因该是可以的;
请问抱什么错误吗!
⑥ python怎样读取pcap文件
程序如下:
#!/usr/bin/env python
#coding=utf-8
#读取pcap文件,解析相应的信息,为了在记事本中显示的方便,把二进制的信息
import struct
fpcap = open('test.pcap','rb')
ftxt = open('result.txt','w')
string_data = fpcap.read()
#pcap文件包头解析
pcap_header = {}
pcap_header['magic_number'] = string_data[0:4]
pcap_header['version_major'] = string_data[4:6]
pcap_header['version_minor'] = string_data[6:8]
pcap_header['thiszone'] = string_data[8:12]
pcap_header['sigfigs'] = string_data[12:16]
pcap_header['snaplen'] = string_data[16:20]
pcap_header['linktype'] = string_data[20:24]
#把pacp文件头信息写入result.txt
ftxt.write("Pcap文件的包头内容如下: \n")
for key in ['magic_number','version_major','version_minor','thiszone',
'sigfigs','snaplen','linktype']:
ftxt.write(key+ " : " + repr(pcap_header[key])+'\n')
#pcap文件的数据包解析
step = 0
packet_num = 0
packet_data = []
pcap_packet_header = {}
i =24
while(i<len(string_data)):
#数据包头各个字段
pcap_packet_header['GMTtime'] = string_data[i:i+4]
pcap_packet_header['MicroTime'] = string_data[i+4:i+8]
pcap_packet_header['caplen'] = string_data[i+8:i+12]
pcap_packet_header['len'] = string_data[i+12:i+16]
#求出此包的包长len
packet_len = struct.unpack('I',pcap_packet_header['len'])[0]
#写入此包数据
packet_data.append(string_data[i+16:i+16+packet_len])
i = i+ packet_len+16
packet_num+=1
#把pacp文件里的数据包信息写入result.txt
for i in range(packet_num):
#先写每一包的包头
ftxt.write("这是第"+str(i)+"包数据的包头和数据:"+'\n')
for key in ['GMTtime','MicroTime','caplen','len']:
ftxt.write(key+' : '+repr(pcap_packet_header[key])+'\n')
#再写数据部分
ftxt.write('此包的数据内容'+repr(packet_data[i])+'\n')
ftxt.write('一共有'+str(packet_num)+"包数据"+'\n')
ftxt.close()
fpcap.close()
最终得到的result文件如下所示:字段显示的都是十六进制,其中的数据部分和wireshark打开,显示的十六进制窗口一样。
⑦ 在linux下,python怎么才能抓到网卡上的所有TCP数据包
Ethereal 自带许多协议的 decoder,简单,易用,基于winpcap的一个开源的软件.但是它的架构并不灵活,如何你要加入一个自己定义的的解码器,得去修改 Ethereal的代码,再重新编译,很烦琐.对于一般的明文 协议,没有什么问题,但是对于加密协议,比如网络游戏,客户端程序一般会在刚连接上的时候,发送一个随机密钥,而后的报文都会用这个密钥进行加密,如此. 要想破解,得要有一个可编程的抓包器.
libpcap是一个不错的选择,但是对于抓包这样需要反复进行”试 验->修改”这个过程的操作,c 语言显然不是明智的选择.
Python提供了几个libpcapbind。在windows平台上,你需要先安装winpcap,如果你已经安装了Ethereal非常好用
一个规范的抓包过程
import pcap
import dpkt
pc=pcap.pcap() #注,参数可为网卡名,如eth0
pc.setfilter('tcp port 80') #设置监听过滤器
for ptime,pdata in pc: #ptime为收到时间,pdata为收到数据
print ptime,pdata #...
对抓到的以太网V2数据包(raw packet)进行解包
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 data.dport==80:
print p.data.data.data # by gashero
一些显示参数
nrecv,ndrop,nifdrop=pc.stats()
返回的元组中,第一个参数为接收到的数据包,(by gashero)第二个参数为被核心丢弃的数据包。
⑧ python2.7 怎么进行抓包和解包
1、抓包,可以下载winpcapy 或者自己加载winpcap动态库
2、解包,使用dpkt解析
参考程序,基于进程抓包QPA工具
⑨ python pcap 导入之后第一行程序就有问题!急求解决办法!!
这个东西可能是两个原因。一个就是少安装了pcap对应的驱动程序,第二个可能是操作系统版本问题。 你可以在一个xp操作系统上试验。
另外pcap应该有新版本。支持python2.7的。如果没有自己下源码编译一下。
不过,还是建议你用linux来做试验。这样全都变得简单了。
⑩ 如何利用libpcap和Python嗅探数据包
一提到Python获取数据包的方式,相信很多Python爱好者会利用Linux的libpcap软件包或利用Windows下的WinPcap可移植版的方式进行抓取数据包,然后再利用dpkt软件包进行协议分析,我们这里想换一个角度去思考:
1. Python版本的pcap存储内存数据过小,也就是说缓存不够,在高并发下容易发生丢包现象,其实C版本的也同样存在这样的问题,只不过Python版本的缓存实在是过低,让人很郁闷。
2. dpkt协议分析并非必须,如果你对RFC 791和RFC 793等协议熟悉的话,完全可以使用struct.unpack的方式进行分析。
如果你平常习惯使用tcpmp抓取数据包的话,完全可以使用它来代替pcap软件包,只不过我们需要利用tcpmp将抓取的数据以pcap格式进行保存,说道这里大家一定会想到Wireshark工具,具体命令如下:
tcpmp dst 10.13.202.116 and tcp dst port 80 -s 0 -i eth1 -w ../pcap/tcpmp.pcap -C 1k -W 5
我们首先需要对pcap文件格式有所了解,具体信息大家可以参考其他资料文档,我这里只说其重要的结构体组成,如下:
sturct pcap_file_header
{
DWORD magic;
WORD version_major;
WORD version_minor;
DWORD thiszone;
DWORD sigfigs;
DWORD snaplen;
DWORD linktype;
}
struct pcap_pkthdr
{
struct timeval ts;
DWORD caplen;
DWORD len;
}
struct timeval
{
DWORD GMTtime;
DWORD microTime;
}
这里需要说明的一点是,因为在Python的世界里一切都是对象,所以往往Python在处理数据包的时候感觉让人比较麻烦。Python提供了几个libpcapbind,http://monkey.org/~gsong/pypcap/这里有 一个最简单的。在windows平台上,你需要先安装winpcap,如果你已经安装了Ethereal非常好用。一个规范的抓包过程:
import pcap
import dpkt
pc=pcap.pcap() #注,参数可为网卡名,如eth0
pc.setfilter('tcp port 80') #设置监听过滤器
for ptime,pdata in pc: #ptime为收到时间,pdata为收到数据
print ptime,pdata #...
对抓到的以太网V2数据包(raw packet)进行解包:
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 data.dport==80:
print p.data.data.data
一些显示参数nrecv,ndrop,nifdrop=pc.stats()返回的元组中,第一个参数为接收到的数据包,第二个参数为被核心丢弃的数据包。
至于对于如何监控tcpmp生成的pcap文件数据,大家可以通过pyinotify软件包来实现,如下:
class Packer(pyinotify.ProcessEvent):
def __init__(self, proct):
self.proct = proct
self.process = None
def process_IN_CREATE(self, event):
logger.debug("create file: %s in queue" % self.process_IF_START_THREAD(event))
def process_IN_MODIFY(self, event):
self.process_IF_START_THREAD(event)
logger.debug("modify file: %s in queue" % self.process_IF_START_THREAD(event))
def process_IN_DELETE(self, event):
filename = os.path.join(event.path, event.name)
logger.debug("delete file: %s" % filename)
def process_IF_START_THREAD(self, event):
filename = os.path.join(event.path, event.name)
if filename != self.process:
self.process = filename
self.proct.put(filename)
if self.proct.qsize() > 1:
try:
logger.debug("create consumer proct.qsize: %s" % self.proct.qsize())
consumer = Consumer(self.proct)
consumer.start()
except Exception, errmsg:
logger.error("create consumer failed: %s" % errmsg)
return filename
class Factory(object):
def __init__(self, proct):
self.proct = proct
self.manager = pyinotify.WatchManager()
self.mask = pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_MODIFY
def work(self):
try:
try:
notifier = pyinotify.ThreadedNotifier(self.manager, Packer(self.proct))
notifier.start()
self.manager.add_watch("../pcap", self.mask, rec = True)
notifier.join()
except Exception, errmsg:
logger.error("create notifier failed: %s" % errmsg)
except KeyboardInterrupt, errmsg:
logger.error("factory has been terminated: %s" % errmsg)
在获得要分析的pcap文件数据之后,就要对其分析了,只要你足够了解pcap文件格式就可以了,对于我们来讲只需要获得TCP数据段的数据即可,如下:
class Writer(threading.Thread):
def __init__(self, proct, stack):
threading.Thread.__init__(self)
self.proct = proct
self.stack = stack
self.pcap_pkthdr = {}
def run(self):
while True:
filename = self.proct.get()
try:
f = open(filename, "rb")
readlines = f.read()
f.close()
offset = 24
while len(readlines) > offset:
self.pcap_pkthdr["len"] = readlines[offset+12:offset+16]
try:
length = struct.unpack("I", self.pcap_pkthdr["len"])[0]
self.stack.put(readlines[offset+16:offset+16+length])
offset += length + 16
except Exception, errmsg:
logger.error("unpack pcap_pkthdr failed: %s" % errmsg)
except IOError, errmsg:
logger.error("open file failed: %s" % errmsg)
在获得TCP数据段的数据包之后,问题就简单多了,根据大家的具体需求就可以进行相应的分析了,我这里是想分析其HTTP协议数据,同样也借助了dpkt软件包进行分析,如下:
def worker(memcache, packet, local_address, remote_address):
try:
p = dpkt.ethernet.Ethernet(packet)
if p.data.__class__.__name__ == "IP":
srcip = "%d.%d.%d.%d" % tuple(map(ord, list(p.data.src)))
dstip = "%d.%d.%d.%d" % tuple(map(ord, list(p.data.dst)))
if p.data.data.__class__.__name__ == "TCP":
tcpacket = p.data.data
if tcpacket.dport == 80 and dstip == local_address:
srcport = tcpacket.sport
key = srcip + ":" + str(srcport)
if tcpacket.data:
if not memcache.has_key(key):
memcache[key] = {}
if not memcache[key].has_key("response"):
memcache[key]["response"] = None
if memcache[key].has_key("data"):
memcache[key]["data"] += tcpacket.data
else:
memcache[key]["data"] = tcpacket.data
else:
if memcache.has_key(key):
memcache[key]["response"] = dpkt.http.Request(memcache[key]["data"])
try:
stackless.tasklet(connection)(memcache[key]["response"], local_address, remote_address)
stackless.run()
except Exception, errmsg:
logger.error("connect remote remote_address failed: %s", errmsg)
logger.debug("old headers(none content-length): %s", memcache[key]["response"])
memcache.pop(key)
except Exception, errmsg:
logger.error("dpkt.ethernet.Ethernet failed in worker: %s", errmsg)
如果大家只是想单纯的获取IP地址、端口、流量信息,那么问题就更简单了,这里只是抛砖引玉。另外再提供一段代码供参考:
import pcap, dpkt, struct
import binascii
def main():
a = pcap.pcap()
a.setfilter('udp portrange 4000-4050')
try:
for i,pdata in a:
p=dpkt.ethernet.Ethernet(pdata)
src='%d.%d.%d.%d' % tuple(map(ord,list(p.data.src)))
dst='%d.%d.%d.%d' % tuple(map(ord,list(p.data.dst)))
sport = p.data.data.sport
dport = p.data.data.dport
qq = int( binascii.hexlify(p.data.data.data[7:11]) , 16 )
print 'QQ: %d, From: %s:%d , To: %s:%d' % (qq,src,sport,dst,dport)
except Exception,e:
print '%s' % e
n = raw_input()
if __name__ == '__main__':
main()