因为工作需要,需要分析wirshark的抓包数据。数据有的是在比特位中。不方便查找。而lua语言又不愿意去学,所以用python解析后,输出日志。帮助分析.
1.tcp分析
python
from dpkt.tcp import TCP
from scapy.all import *
from datetime import datetime, timedelta
import pytz
import datetime
from datetime import datetime
def main(file_path,tcp_ip,tcp_port):
pkts = rdpcap(file_path)
for pkt in pkts:
if IP in pkt and TCP in pkt:
if pkt[IP].dst == tcp_ip and pkt[TCP].dport == tcp_port:
# if pkt[IP].dst == "225.0.0.10" and pkt[TCP].dport == 12306 and len(pkt) == 25:
if len(pkt.load) == 18:
print("*" * 50)
print("Time: ", datetime.fromtimestamp(pkt.time), "Second byte: ", pkt[Raw].load[2])
main('E:\\abs\\shak\\1.pcapng', "225.0.0.10", 12306)
2.udp分析
python
from dpkt.ip import IP
from dpkt.udp import UDP
from scapy.all import *
import datetime
from datetime import datetime
def main(file_path,udp_ip,udp_port):
pkts = rdpcap(file_path)
for pkt in pkts:
if IP in pkt and UDP in pkt:
if pkt[IP].dst == udp_ip and pkt[UDP].dport == udp_port:
if len(pkt.load) == 18:
print("*"*50)
print("Time: ", datetime.fromtimestamp(pkt.time),"Second byte: ", pkt[Raw].load[2])
if pkt[Raw].load[9] == 0x0a:
print("*" * 50)
# 打印完整的全部数据
#print("Time: ", datetime.fromtimestamp(pkt.time),pkt.show())
#只打印对应的数据包
print("Time: ", datetime.fromtimestamp(pkt.time),pkt.load)
main('E:\\abs\\shak\\1.pcapng',"225.0.0.10",12306)
3.根据比特位取值,保存
python
from dpkt.ip import IP
from dpkt.udp import UDP
from scapy.all import *
import datetime
from datetime import datetime
def main(file_path,udp_ip,udp_port):
pkts = rdpcap(file_path)
with open("E:\\abs\\shak\\output.txt", "w") as f:
for pkt in pkts:
# 过滤ip
if IP in pkt and UDP in pkt and pkt[IP].dst == udp_ip and pkt[UDP].dport == udp_port:
# 过滤长度
if len(pkt.load) == 18:
#过滤功能码,同时可以计算某个字节的比特位
if pkt[Raw].load[9] == 0x0a:
bit_one = (pkt[Raw].load[10] >> 1) & 0x01
bit_two = (pkt[Raw].load[10] >> 2) & 0x01
bit_three = (pkt[Raw].load[10] >> 3) & 0x01
bit_four = (pkt[Raw].load[10] >> 4) & 0x01
bit_five = (pkt[Raw].load[10] >> 5) & 0x01
bit_six = (pkt[Raw].load[10] >> 6) & 0x01
bit_seven = (pkt[Raw].load[10] >> 7) & 0x01
data = "Time:" + "\t" + str(datetime.fromtimestamp(pkt.time)) + "\t" + "data:" + str(bit_one)\
+" "+str(bit_two)+" "+str(bit_three)+" "+str(bit_four)+" "+str(bit_five)+" "+str(bit_six)\
+" "+str(bit_seven)+ "\n"
f.write(data)
#print("Time: ", datetime.fromtimestamp(pkt.time),pkt.show())
print("Time: ", datetime.fromtimestamp(pkt.time),pkt.load)
data1 = "Time:"+"\t" +str(datetime.fromtimestamp(pkt.time))+"\t"+"data:"+str(pkt.load)+"\n"
f.write(data1)