當前位置:首頁 » 編程語言 » 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-04-25 12:40:04 瀏覽:965
低配置游戲玩哪個平台 發布:2024-04-25 12:35:04 瀏覽:559
glinux下載 發布:2024-04-25 12:30:09 瀏覽:84
安卓手機可以用的谷歌叫什麼 發布:2024-04-25 12:05:57 瀏覽:943
linux改變用戶所屬組 發布:2024-04-25 11:50:33 瀏覽:469
rsa加密演算法java代碼 發布:2024-04-25 11:40:07 瀏覽:883
如何改變拉桿箱上的初始密碼 發布:2024-04-25 11:17:23 瀏覽:799
內網掛代理虛擬機如何配置網卡 發布:2024-04-25 11:15:06 瀏覽:687
明日之後緩存怎麼清理 發布:2024-04-25 11:14:56 瀏覽:205
華為mate30怎麼退回安卓版 發布:2024-04-25 11:08:49 瀏覽:898