Python ARP欺骗攻击检测与记录代码示例

以下代码示例展示了如何使用Python和Scapy库检测ARP欺骗攻击,并记录攻击源的IP和MAC地址。

def detect_attack():
    with open('clients.txt', 'r') as f:
        clients = f.readlines()
        for client in clients:
            ip = client.split()[0]
            mac = client.split()[1]
            sniff_filter = 'arp and src host ' + ip
            sniff_timeout = 10
            sniff_count = 0
            sniff_packets = sniff(filter=sniff_filter, timeout=sniff_timeout)
            for packet in sniff_packets:
                sniff_count += 1
                # 检测伪造源MAC地址
                if packet[ARP].hwsrc == '00:00:00:00:00:00':
                    with open('detection_log.txt', 'a') as f:
                        f.write('警告' + '检测到伪造源MAC地址为' + packet[ARP].psrc + '的ARP欺骗攻击!\n')
            if sniff_count > 100:
                messagebox.showwarning('警告', '检测到攻击源IP地址为' + ip + ',MAC地址为' + mac + '!')
                with open('detection_log.txt', 'a') as f:
                    f.write('警告' + '检测到攻击源IP地址为' + ip + ',MAC地址为' + mac + '!\n')
            else:
                messagebox.showinfo('提示', '未检测到攻击源!')
                with open('detection_log.txt', 'a') as f:
                    f.write('提示' + '未检测到攻击源!\n')
            return

代码说明:

  1. 代码首先从clients.txt文件中读取IP和MAC地址对。
  2. 使用Scapy库的sniff()函数嗅探网络流量,过滤条件为arp and src host ip,即只捕获目标IP地址的ARP请求。
  3. 代码循环遍历嗅探到的数据包,判断源MAC地址是否为'00:00:00:00:00:00',如果是则认为是伪造的MAC地址,并将其记录到detection_log.txt文件中。
  4. 此外,代码还统计了sniff_count,如果超过100则认为是攻击行为,并记录攻击源IP和MAC地址到detection_log.txt文件中。

注意事项:

  • 代码中的'00:00:00:00:00:00'为一个通用的伪造MAC地址,实际应用中可能会有其他伪造MAC地址。
  • 代码需要安装Scapy库,可以使用pip install scapy命令安装。
  • 代码需要运行在具有网络嗅探权限的环境中。

扩展阅读:

本文提供了一个简单的ARP欺骗攻击检测示例,实际应用中可能需要根据具体场景进行调整和完善。

Python ARP欺骗攻击检测与记录代码示例

原文地址: https://www.cveoy.top/t/topic/jojk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录