环境:python3.5,pycharm,wireshark
利用pyshark读取报文中的相应字段主要是要知道Capture对象各个属性个方法都着哪些信息,然后再一层一层读取出来。
其中apply_on_packets() 方法是另一种遍历数据包的方式,它接受一个函数作为参数并将之作用于所有的数据包。
离线版本:分析已有的pcap文件:
import pyshark
cap = pyshark.FileCapture(input_file="D:\\test2.pcap",display_filter="browser")
#capture.sniff(timeout=10)
count = []
def counter(*args):
count.append(args[0])
# print(args[0].ip.src)
#print(args[0].browser.__dict__['_all_fields'],type(args[0].browser.__dict__))
if '_all_fields' in args[0].browser.__dict__:
if 'browser.server' in args[0].browser.__dict__['_all_fields']:
if args[0].browser.__dict__['_all_fields']['browser.windows_version']=='Windows 7 or Windows Server 2008 R2':
win_v = 'Windows 7 or Windows Server 2008 R2'
else: win_v = 'Windows 10'
print('ip地址:',args[0].ip.src.ljust(14),';','设备名:',args[0].browser.__dict__['_all_fields']['browser.server'].ljust(20),';','windows版本:',win_v.ljust(35),';',end=" ")
print('服务种类:',end=" ")
for key,value in args[0].browser.__dict__['_all_fields'].items():
if 'browser.server_type' in key:
if value=='1':
print(key[20:],end=", ")
print("")
print(dir(cap[0].browser))
print(type(cap[0]))
cap.apply_on_packets(counter, timeout=10000)
print(len(count))
#print(count[1])
# print(len(count))
# print(dir(cap[0]))
# a=cap[0]
# #print(a)
# print(a.ip.__dir__)
# print(a.ip.dst)
# print(dir(a.layers[1]))
# for pkt in cap:
# print("第%d条:"%i)
# print(pkt)
# i=i+1
# if i>10:
# break
# print(cap[5].highest_layer)
在线版本,抓包的同时分析:
import pyshark
# tshark_path = 'D:\\good\\Wireshark\\tshark.exe'
# cap = pyshark.FileCapture(input_file="D:\\test2.pcap",display_filter="browser")
tshark_path = 'D:\\good\\Wireshark\\tshark.exe'
cap = pyshark.LiveCapture(output_file="test_pcap4.pcap",interface="以太网",display_filter="browser",
tshark_path=tshark_path)
cap.sniff(timeout=100)
count = []
def counter(*args):
count.append(args[0])
# print(args[0].ip.src)
#print(args[0].browser.__dict__['_all_fields'],type(args[0].browser.__dict__))
if '_all_fields' in args[0].browser.__dict__:##brower层的信息存在__dict__字典中
if 'browser.server' in args[0].browser.__dict__['_all_fields']:
if args[0].browser.__dict__['_all_fields']['browser.windows_version']=='Windows 7 or Windows Server 2008 R2':
win_v = 'Windows 7 or Windows Server 2008 R2'
else: win_v = 'Windows 10'
print('ip地址:',args[0].ip.src.ljust(14),';','设备名:',args[0].browser.__dict__['_all_fields']['browser.server'].ljust(20),';','windows版本:',win_v.ljust(35),';',end=" ")
print('服务种类:',end=" ")
for key,value in args[0].browser.__dict__['_all_fields'].items():
if 'browser.server_type' in key:
if value=='1':
print(key[20:],end=", ")
print("")
print(dir(cap[0].browser))
print(type(cap[0]))
cap.apply_on_packets(counter, timeout=10000)
print(len(count))
#print(count[1])
# print(len(count))
# print(dir(cap[0]))
# a=cap[0]
# #print(a)
# print(a.ip.__dir__)
# print(a.ip.dst)
# print(dir(a.layers[1]))
# for pkt in cap:
# print("第%d条:"%i)
# print(pkt)
# i=i+1
# if i>10:
# break
# print(cap[5].highest_layer)