因工作需要,需要在服务器上抓取指定源IP的流量,分析出源IP、目的IP、目的端口、访问次数等信息,以下是抓包分析代码:
from scapy.all import *
from scapy.layers.l2 import Ether
from scapy.layers.inet import IP, TCP,UDP
import time
# 指定要追踪的源IP地址
source_ip_to_track = '10.0.0.2' # 替换为实际需要追踪的源IP地址
destination_port_to_track = 2000 # 替换为实际需要追踪的目的端口
ip_dst_counts = {}
def packet_analyzer(packet):
if IP in packet and packet[IP].src == source_ip_to_track:
if TCP in packet and packet[TCP].dport == destination_port_to_track or \
UDP in packet and packet[UDP].dport == destination_port_to_track:
dst_ip = packet[IP].dst
# 计数统计
ip_dst_counts[dst_ip] = ip_dst_counts.get(dst_ip, 0) + 1
# 打印信息
print(f"Source IP: {packet[IP].src}, Destination IP: {dst_ip}, Destination Port: {destination_port_to_track}")
# 开始抓包并设置抓包时长为5分钟(300秒)
start_time = time.time()
try:
sniff(filter=f"ip src {source_ip_to_track} and (tcp port {destination_port_to_track} or udp port {destination_port_to_track})", prn=packet_analyzer, timeout=30)
except KeyboardInterrupt:
pass # 如果用户手动中断,则停止抓包
# 抓包结束后计算并打印结果
end_time = time.time()
elapsed_time = end_time - start_time
print("\nTraffic Analysis Summary:")
for dst_ip, count in ip_dst_counts.items():
print(f"Source IP: {source_ip_to_track}, Target IP: {dst_ip}, Target Port: {destination_port_to_track}, Count: {count}")