首先打开Wireshark,在联网的网卡上开始抓包过程,再用浏览器打开网页,关闭网页并结束抓包过程,然后将抓包内容保存为pcapng格式的文件。对上述pcapng文件,使用Scapy库或其他解析库,获取到tcp三报文连接或tcp四报文释放的信息,获取到相关信息后,再用Matplot库绘制三报文连接或四报文释放的过程
时间: 2024-03-14 20:48:58 浏览: 150
好的,下面是一个Python程序,用于解析pcapng文件并绘制TCP三次握手和四次挥手的过程。首先,我们需要安装必要的Python库:`scapy`和`matplotlib`。可以使用以下命令进行安装:
```
pip install scapy
pip install matplotlib
```
下面是完整的Python代码:
```python
import matplotlib.pyplot as plt
import pandas as pd
from scapy.all import *
# 载入pcapng文件
packets = rdpcap('example.pcapng')
# 定义TCP连接的状态
CLOSED, LISTEN, SYN_SENT, SYN_RCVD, ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT, CLOSING, LAST_ACK, TIME_WAIT = range(11)
# 初始化TCP连接状态
state = CLOSED
# 定义三次握手和四次挥手的数据包数量
syn_count = 0
syn_ack_count = 0
ack_count = 0
fin_count = 0
fin_ack_count = 0
# 定义数据包时间戳和TCP序列号
timestamps = []
seq_nums = []
# 处理每个数据包
for packet in packets:
if TCP in packet:
tcp = packet[TCP]
if tcp.flags & 0x02 and state == LISTEN:
# 收到SYN,进入SYN_RCVD状态
state = SYN_RCVD
syn_count += 1
timestamps.append(packet.time)
seq_nums.append(tcp.seq)
elif tcp.flags & 0x02 and state == CLOSED:
# 发送SYN,进入SYN_SENT状态
state = SYN_SENT
syn_count += 1
timestamps.append(packet.time)
seq_nums.append(tcp.seq)
elif tcp.flags & 0x10 and state == SYN_SENT:
# 收到ACK,进入ESTABLISHED状态
state = ESTABLISHED
ack_count += 1
timestamps.append(packet.time)
seq_nums.append(tcp.seq)
elif tcp.flags & 0x10 and state == SYN_RCVD:
# 发送ACK,进入ESTABLISHED状态
state = ESTABLISHED
syn_ack_count += 1
timestamps.append(packet.time)
seq_nums.append(tcp.seq)
elif tcp.flags & 0x01 and state == ESTABLISHED:
# 发送FIN,进入FIN_WAIT_1状态
state = FIN_WAIT_1
fin_count += 1
timestamps.append(packet.time)
seq_nums.append(tcp.seq)
elif tcp.flags & 0x10 and state == FIN_WAIT_1:
# 收到ACK,进入FIN_WAIT_2状态
state = FIN_WAIT_2
ack_count += 1
timestamps.append(packet.time)
seq_nums.append(tcp.seq)
elif tcp.flags & 0x01 and state == FIN_WAIT_2:
# 收到FIN,进入TIME_WAIT状态
state = TIME_WAIT
fin_ack_count += 1
timestamps.append(packet.time)
seq_nums.append(tcp.seq)
elif tcp.flags & 0x10 and state == TIME_WAIT:
# 发送ACK,结束连接
state = CLOSED
ack_count += 1
timestamps.append(packet.time)
seq_nums.append(tcp.seq)
# 绘制TCP连接状态的时序图
df = pd.DataFrame({'timestamp': timestamps, 'seq_num': seq_nums})
df['state'] = state
df['event'] = ''
df.loc[df.state == SYN_RCVD, 'event'] = 'SYN'
df.loc[df.state == SYN_SENT, 'event'] = 'SYN'
df.loc[df.state == ESTABLISHED, 'event'] = 'ACK'
df.loc[df.state == FIN_WAIT_1, 'event'] = 'FIN'
df.loc[df.state == FIN_WAIT_2, 'event'] = 'ACK'
df.loc[df.state == TIME_WAIT, 'event'] = 'FIN'
df = df[['timestamp', 'event']]
df.plot(x='timestamp', y='event', drawstyle='steps-post')
plt.title('TCP Connection State')
plt.xlabel('Time (s)')
plt.ylabel('Event')
plt.show()
# 打印三次握手和四次挥手的数据包数量
print('SYN: {} SYN-ACK: {} ACK: {}'.format(syn_count, syn_ack_count, ack_count))
print('FIN: {} FIN-ACK: {}'.format(fin_count, fin_ack_count))
```
这个程序将绘制TCP连接状态的时序图,并打印三次握手和四次挥手的数据包数量。希望对您有所帮助!
阅读全文