Python ARP 攻击检测及源地址记录方法
使用 Python 代码检测 ARP 攻击并记录攻击源地址
本文将介绍如何使用 Python 代码检测 ARP 攻击并记录攻击源地址。
1. 代码实现
from scapy.all import ARP, Ether, srp
from tkinter import messagebox
# 获取 MAC 地址函数
def get_mac(ip):
arp = ARP(pdst=ip)
ether = Ether(dst='ff:ff:ff:ff:ff:ff')
packet = ether/arp
result = srp(packet, timeout=3, verbose=False)[0]
return result[0][1].hwsrc
# 检测 ARP 攻击函数
def detect_attack():
with open('clients.txt', 'r') as f:
clients = f.readlines()
for client in clients:
ip = client.split()[0]
mac = get_mac(ip)
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
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')
# 安装 scapy 库
pip install scapy
# 运行代码
detect_attack()
2. 代码说明
get_mac(ip)函数使用 scapy 库获取指定 IP 地址的 MAC 地址。detect_attack()函数读取clients.txt文件中的 IP 地址,并逐个使用get_mac()函数获取对应的 MAC 地址。- 使用
sniff()函数对网络进行嗅探,并设置嗅探过滤器为arp and src host <IP 地址>,以过滤掉非 ARP 攻击包和非目标 IP 地址的 ARP 包。 - 使用
sniff_count计数器记录嗅探到的 ARP 包数量,如果数量超过 100,则认为可能存在 ARP 攻击。 - 使用
messagebox.showwarning()显示警告信息,并使用messagebox.showinfo()显示提示信息。 - 使用
open('detection_log.txt', 'a')将攻击信息写入日志文件,并使用f.write()方法写入内容。
3. 注意事项
clients.txt文件应包含需要检测的 IP 地址,每行一个 IP 地址。detection_log.txt文件用于记录检测到的攻击信息。- 该代码仅供参考,实际应用中可能需要根据具体情况进行调整。
4. 总结
本文介绍了使用 Python 代码检测 ARP 攻击并记录攻击源地址的方法。通过使用 scapy 库和嗅探技术,可以有效地检测 ARP 攻击,并记录攻击源地址。希望本文能对您有所帮助。
原文地址: https://www.cveoy.top/t/topic/jojC 著作权归作者所有。请勿转载和采集!