最近一直在使用做流量分析,今天把 scapy 部分做一个总结。
Python 的 scapy 库可以方便的抓包与解析包,无奈资料很少,官方例子有限,大神博客很少提及, 经过一番尝试后,总结以下几点用法以便大家以后使用。
from scapy.all import * from scapy.layers.inet import * import pyshark import numpy as np #第一种抓包方式,指定源目的IP pkt = IP(src="192.168.43.47", dst="36.155.132.76")/ICMP() #src=本机地址 dst=CMD ping www.baidu.com的地址 res = sr1(pkt) print(res.summary()) print(res.show()) #wrpcap("test10.cap",res) #第二种抓包方式,sniff函数,看指定网卡的抓包信息 print(conf.ifaces) def cell(mes): print(mes.summary) pkt = sniff(filter="icmp and host 192.168.3.7", iface = 'Intel(R) Dual Band Wireless-AC 8265', prn=cell,count = 5) #iface=指定网卡 filter=指定条件过滤包信息 count=抓5个包 prn=cell 调用cell输出抓包内容 wrpcap("test1.cap",pkt) #wrpcap将抓包信息存入test1.cap ####解析CAP内容 capfile="test1.cap" sourceip=[] distip=[] protocl =[] capture = pyshark.FileCapture(capfile) print("===capture====",capture) for packet in capture: src_ip = packet.ip.src dist_ip = packet.ip.dst pro = packet.highest_layer sourceip.append(src_ip) distip.append(dist_ip) protocl.append(pro) print(f"Packet: {pro} from {src_ip} to {dist_ip}") print("sourceip",sourceip) print("dest",distip) print("protocl",protocl) source_ips = np.array(sourceip) #数组形IP地址 ['172.31.1.138'] 可以直接用openpyxl去存,ws.append(source_ips) #数组形IP地址 ['153.3.238.110']z 第三中抓包保存文件: def save_pkt(packets): with open('net_pkt.txt','a') as f: for packet in packets: f.write(str(packet)+"\n") pkt = sniff() save_pkt(pkt) packets = rdpcap("pkt.pcap")
#OSPF
from scapy.all import sniff, OSPF
def analyze_ospf_packet(packet):
# 检查数据包是否为OSPF
if packet[OSPF]:
# 打印OSPF数据包的基本信息
print("Received OSPF packet:")
print(f" Type: {packet[OSPF].type}")
print(f" Router ID: {packet[OSPF].router}")
print(f" Area ID: {packet[OSPF].area})
# 使用sniff函数抓取数据包,设置过滤器为ospf
sniff(filter="ospf", prn=analyze_ospf_packet, count=10)
跟多信息的解析
from scapy.all import *
from scapy.packet import *
from scapy.layers.inet import *
# import scapy.all
# ssh和sftp什么关系?
# print(dir(scapy.layers))#查看支持的协议
# print(explore(scapy.layers.inet))
# scapy.layers.inet
# scapy.all
# scapy.packet
# print(explore(scapy.layers.inet))#为何报错
# print(explore(scapy.packet.ls(IP)))#查看报文结构
# print(scapy.packet.ls(IP))
# scapy.packet.ls(IP)
pkt = IP(src='192.168.56.1',dst='192.168.56.100')/ICMP()#/BGP
# print(type(pkt.id))
# print(pkt)
print(type(pkt))
res = sr1(pkt)#发送出去并接收,具体哪个网卡要指定
print(res.summary())
print(type(res))
# res.show()
print(res.layers())
# # res.copy_fields_dict('IP')
# # print(res.get_field('chksum'))
# print(res.getfieldval('src'))
# # print(res)#自带函数不能解析吗?
# wrpcap("test_send.cap",pkt)#因为是把原文0x写进去,再用Destination:去提取信息,可以用wireshark软件打开,也可以open以后用wireshark包?和numpy包?
# wrpcap("test_receive.cap",res)
# res用numpy转换为字典再获取对应字段值?
# print(conf.ifaces)#列出本机网卡
# print(conf.route)#本机所有路由
# def cell(pkt):
# print(pkt.summary)
# sniff(filter='icmp and host 192.168.56.100',iface='VirtualBox Host-Only Ethernet Adapter',prn=cell,count=100)#prn是回调函数,不用括号,计数100个结束