Python監控網絡通信可以幫助我們了解網絡數據的傳輸情況,從而更好地調試和優化網絡應用。在Python中,有很多強大的庫可以用于網絡通信的監控與分析,比如tcpdump、pcapy、pyshark、Scapy等等。
import pyshark
import time
def print_packet(packet):
try:
if packet.transport_layer == "TCP":
src_ip = packet.ip.src
src_port = packet.tcp.srcport
dst_ip = packet.ip.dst
dst_port = packet.tcp.dstport
payload = packet.tcp.payload.data.hex()
print("TCP packet sent from {}:{} to {}:{} with payload {}".format(src_ip, src_port, dst_ip, dst_port, payload))
elif packet.transport_layer == "UDP":
src_ip = packet.ip.src
src_port = packet.udp.srcport
dst_ip = packet.ip.dst
dst_port = packet.udp.dstport
payload = packet.udp.payload.data.hex()
print("UDP packet sent from {}:{} to {}:{} with payload {}".format(src_ip, src_port, dst_ip, dst_port, payload))
except AttributeError as error:
pass
capture = pyshark.LiveCapture(interface='eth0')
capture.sniff(timeout=10)
for packet in capture.sniff_continuously(packet_count=10):
print_packet(packet)
time.sleep(1)
上面的代碼使用了pyshark庫來捕獲網絡數據包,并對TCP和UDP數據包進行了解析,輸出源IP、源端口、目標IP、目標端口以及數據包的內容。在實際應用中,我們可以根據需要對數據包進行分析和過濾,以便更好地監控網絡通信。