当前位置:首页 » 编程语言 » pcap抓包python

pcap抓包python

发布时间: 2023-04-02 02:07:45

python pcap 导入之后第一行程序就有问题!急求解决办法!!

这个东西可能是两个原因。一个就是少安装了pcap对应的驱动程序,第二个可能是操作系统版本问题。 你可以在一个xp操作系统上试验。

另外pcap应该有新版本。支持python2.7的。如果没有自己下源码编译一下迹液。

不过,还是岁销建议乎州游你用linux来做试验。这样全都变得简单了。

② 低版本通杀工具怎么用

两种抓包模式

  • Spawn 模式,直接抓包

    python r0capture.py -U -f 包名

  • Attach 模式,将抓包内袜数容保存成pcap格式文件

    python r0capture.py -U 包名 -p 文件名.pcap

    建议使用Attach模式,从感兴趣的地方开始抓包,并且保存成pcap文件,供后续使用Wireshark进行分析。

  • 导入脚本项目

  • 导入到Pycharm项目弊好吵中

  • 安装项目所需的包

    pip install win_inet_pton

    pip install hexmp

    pip install loguru

  • 在开启的命令行中两种方式的任意一种进行抓包,建议使用Attach模式,从感兴趣的地方开始抓包,并且保存成pcap文件。

    开始抓包

  • 获取应用包名

    1.adb shell am monitor
    2.启动需要获取包名的应用
    3.窗口就会打印出来当前应用的包名

  • 给应用添加读取存储空间权限

  • 启动frida-server

    adb sehll
    su
    cd /data/local/tmp/
    ./frida-server &
    ps | grep frida

  • Spawn 模式,直接抓包

  • Attach 模式租侍,将抓包内容保存成pcap格式文件

    先打开需要抓包的应用,然后在命令行输入

    python r0capture.py -U com.dianping.v1 -p 123.pcap

    Ctrl+C 结束,如果数据量很大的话,需要等待一会才能彻底关闭

  • 分析数据

③ python程序分析pcap文件的丢包率问题,

使用scapy、scapy_http就可以方便的对pcap包中的http数据包进行解析

#!/usr/bin/env python
try:
import scapy.all as scapy
except ImportError:
import scapy

try:
# This import works from the project directory
import scapy_http.http
except ImportError:
# If you installed this package via pip, you just need to execute this
from scapy.layers import http

packets = scapy.rdpcap('f:\\abc123.pcap')
for p in packets:
print '=' * 78
[python] view plain
#print p.show()
for f in p.payload.fields_desc:
if f.name == 'src' or f.name == 'dst':
ct = scapy.conf.color_theme
vcol = ct.field_value
fvalue = p.payload.getfieldval(f.name)
reprval = f.i2repr(p.payload,fvalue)
print "%s : %s" % (f.name, reprval)

for f in p.payload.payload.fields_desc:
if f.name == 'load':
ct = scapy.conf.color_theme
vcol = ct.field_value
fvalue = p.payload.getfieldval(f.name)
reprval = f.i2repr(p.payload,fvalue)
print "%s : %s" % (f.name, reprval)

其中,p为数据包,scapy_http将其分为:
Ethernet->TCP->RAW三个层次,

使用p.show()函数可以打印出如下结果:
###[ Ethernet ]###
dst = 02:00:00:00:00:39
src = 00:00:00:01:02:09
type = 0x800
###[ IP ]###
version = 4L
ihl = 5L
tos = 0x0
len = 1014
id = 7180
flags =
frag = 0L
ttl = 45
proto = tcp
chksum = 0xbbf9
src = 126.209.59.13
dst = 121.113.176.25
\options \
###[ Raw ]###
load = '.....'

第一层是网络层,包含源、目的mac、ip协议号,第二层是tcp层,第三层包含端口号、http报文
其中每一层均为上一层的payload成员

④ 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打开,显示的十六进制窗口一样。

⑤ python处理pcap追踪tcp流

步骤:
1、标记文件开始,并用亮基来识别文件自己和字节顺序。
2、Major:2Byte:当前文件主渣键租要的版本号。
3、Minor:2Byte:当前文件次要的版本号。
4、ThisZone:4Byte:当地的标准时间,直接写00000000。Python由荷兰数学和计算机科学研究学会的吉多范罗苏姆于1990年代初设计,作为一门叫做ABC语言的替代品,Python提供了高效的高级数如兆据结构,还能简单有效地面向对象编程

⑥ python2.5 使用包pcap和dpkt抓不到包,为什么

要设置网卡的,你可能使用了虚拟网卡

⑦ 如何利用Python嗅探数据包

一提到Python获取数据包的方式,相信很多Python爱好者会利用Linux的libpcap软件包或利用Windows下的WinPcap可移植版的方式进行抓取数据包,然后再利用dpkt软件包进行协议分析,我们这里想换一个角度去思考:1.Python版本的pcap存储内存数据过小,也就是说缓存不够,在高并发下容易发生丢包现象,其实C版本的也同样存在这样的问题,只不过Python版本的缓存实在是过低,让人很郁闷。2.dpkt协议分析并非必须,如果你对RFC791和RFC793等协议熟悉的话,完全可以使用struct.unpack的方式进行分析。如果你平常习惯使用tcpmp抓取数据包的话,完全可以使用它来代替pcap软件包,只不过我们需要利用tcpmp将抓取的数据以pcap格式进行保存,说道这里大家一定会想到Wireshark工具,具体命令如下:tcpmpdst10.13.202.116andtcpdstport80-s0-ieth1-w../pcap/tcpmp.pcap-C1k-W5我们首先需要对pcap文件格式有所了解,具体信息大家可以参考其他资料文档,我这里只说其重要的结构体组成,如下:sturctpcap_file_header{DWORDmagic;WORDversion_major;WORDversion_minor;DWORDthiszone;DWORDsigfigs;DWORDsnaplen;DWORDlinktype;}structpcap_pkthdr{structtimevalts;DWORDcaplen;DWORDlen;}structtimeval{DWORDGMTtime;DWORDmicroTime;}这里需要说明的一点是,因为在Python的世界里一切都是对象,所以往往Python在处理数据包的时候感觉让人比较麻烦。Python提供了几个libpcapbind,这里有一个最简单的。在windows平台上,你需要先安装winpcap,如果你已经安装了Ethereal非常好用。一个规范的抓包过程:importpcapimportdpktpc=pcap.pcap()#注,参数可为网卡名,如eth0pc.setfilter('tcpport80')#设置监听过滤器forptime,pdatainpc:#ptime为收到时间,pdata为收到数据printptime,pdata#对抓到的以太网V2数据包(rawpacket)进行解包:p=dpkt.ethernet.Ethernet(pdata)ifp.data.__class__.__name__=='IP':ip='%d.%d.%d.%d'%tuple(map(ord,list(p.data.dst)))ifp.data.data.__class__.__name__=='TCP':ifdata.dport==80:printp.data.data.data一些显示参数nrecv,ndrop,nifdrop=pc.stats()返回的元组中,第一个参数为接收到的数据包,第二个参数为被核心丢弃的数据包。至于对于如何监控tcpmp生成的pcap文件数据,大家可以通过pyinotify软件包来实现,如下:classPacker(pyinotify.ProcessEvent):def__init__(self,proct):self.proct=proctself.process=Nonedefprocess_IN_CREATE(self,event):logger.debug("createfile:%sinqueue"%self.process_IF_START_THREAD(event))defprocess_IN_MODIFY(self,event):self.process_IF_START_THREAD(event)logger.debug("modifyfile:%sinqueue"%self.process_IF_START_THREAD(event))defprocess_IN_DELETE(self,event):filename=os.path.join(event.path,event.name)logger.debug("deletefile:%s"%filename)defprocess_IF_START_THREAD(self,event):filename=os.path.join(event.path,event.name)iffilename!=self.process:self.process=filenameself.proct.put(filename)ifself.proct.qsize()>1:try:logger.debug("createconsumerproct.qsize:%s"%self.proct.qsize())consumer=Consumer(self.proct)consumer.start()exceptException,errmsg:logger.error("createconsumerfailed:%s"%errmsg)returnfilenameclassFactory(object):def__init__(self,proct):self.proct=proctself.manager=pyinotify.WatchManager()self.mask=pyinotify.IN_CREATE|pyinotify.IN_DELETE|pyinotify.IN_MODIFYdefwork(self):try:try:notifier=pyinotify.ThreadedNotifier(self.manager,Packer(self.proct))notifier.start()self.manager.add_watch("../pcap",self.mask,rec=True)notifier.join()exceptException,errmsg:logger.error("createnotifierfailed:%s"%errmsg)exceptKeyboardInterrupt,errmsg:logger.error("factoryhasbeenterminated:%s"%errmsg)在获得要分析的pcap文件数据之后,就要对其分析了,只要你足够了解pcap文件格式就可以了,对于我们来讲只需要获得TCP数据段的数据即可,如下:classWriter(threading.Thread):def__init__(self,proct,stack):threading.Thread.__init__(self)self.proct=proctself.stack=stackself.pcap_pkthdr={}defrun(self):whileTrue:filename=self.proct.get()try:f=open(filename,"rb")readlines=f.read()f.close()offset=24whilelen(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+16exceptException,errmsg:logger.error("unpackpcap_pkthdrfailed:%s"%errmsg)exceptIOError,errmsg:logger.error("openfilefailed:%s"%errmsg)在获得TCP数据段的数据包之后,问题就简单多了,根据大家的具体需求就可以进行相应的分析了,我这里是想分析其HTTP协议数据,同样也借助了dpkt软件包进行分析,如下:defworker(memcache,packet,local_address,remote_address):try:p=dpkt.ethernet.Ethernet(packet)ifp.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)))ifp.data.data.__class__.__name__=="TCP":tcpacket=p.data.dataiftcpacket.dport==80anddstip==local_address:srcport=tcpacket.sportkey=srcip+":"+str(srcport)iftcpacket.data:ifnotmemcache.has_key(key):memcache[key]={}ifnotmemcache[key].has_key("response"):memcache[key]["response"]=Noneifmemcache[key].has_key("data"):memcache[key]["data"]+=tcpacket.dataelse:memcache[key]["data"]=tcpacket.dataelse:ifmemcache.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()exceptException,errmsg:logger.error("connectremoteremote_addressfailed:%s",errmsg)logger.debug("oldheaders(nonecontent-length):%s",memcache[key]["response"])memcache.pop(key)exceptException,errmsg:logger.error("dpkt.ethernet.Ethernetfailedinworker:%s",errmsg)如果大家只是想单纯的获取IP地址、端口、流量信息,那么问题就更简单了,这里只是抛砖引玉。另外再提供一段代码供参考:importpcap,dpkt,structimportbinasciidefmain():a=pcap.pcap()a.setfilter('udpportrange4000-4050')try:fori,pdataina: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.sportdport=p.data.data.dport =int(binascii.hexlify(p.data.data.data[7:11]),16)print' :%d,From:%s:%d,To:%s:%d'%( ,src,sport,dst,dport)exceptException,e:print'%s'%en=raw_input()if__name__=='__main__':main()

⑧ python2.7 能安装libpcap(抓包)库吗

这个需要下载wpdpack(winpcap的开发包),并且在命令行指明wpdpack的路径。我用过pcap这个包,pyx是依赖于cython来编译成c,然后编译成扩展的,只要有mingw编译器或者vs编译器,还是很容易的

⑨ python利用pcap为什么只能抓到本机的数据包

代码如弯改棚图,只能抓到歼携本机的数据流量

脚本只运行在本机上,只能抓取本机上wlan0的数据埋则。

⑩ 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)
热点内容
安卓在美国怎么下载 发布:2024-05-05 02:31:06 浏览:923
黑莓存储空间 发布:2024-05-05 02:19:50 浏览:274
我的世界矿石岛服务器宣传片 发布:2024-05-05 02:17:19 浏览:613
如何区分安卓原装充电器 发布:2024-05-05 01:41:23 浏览:72
怎么从苹果转移到安卓 发布:2024-05-05 01:41:20 浏览:721
支付宝付款码怎么设置密码 发布:2024-05-05 01:27:36 浏览:878
qtp录制的脚本 发布:2024-05-05 01:14:04 浏览:367
如何安装卡罗拉安卓系统 发布:2024-05-05 01:09:00 浏览:985
sql创建表查询表 发布:2024-05-05 01:00:12 浏览:799
食色抖音上传 发布:2024-05-05 00:55:56 浏览:658