python抓包分析代码

因工作需要,需要在服务器上抓取指定源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}")

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值