基于Linux的Python ARP检测防护软件设计
基于Linux的Python实现ARP检测防护软件设计
本软件使用Python语言在Linux系统上实现ARP检测防护功能,能够获取局域网活动主机的MAC地址和IP地址,检测和防护ARP攻击行为,并记录攻击源的MAC地址和IP地址。
软件功能
- 获取局域网活动主机的MAC地址和IP地址
- 检测ARP攻击行为
- 记录ARP攻击源的MAC地址和IP地址
- 显示攻击源信息
代码实现
arp_scan.py
import os
import re
import socket
import struct
import fcntl
def get_interface_mac(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15].encode()))
return ':'.join('%02x' % b for b in info[18:24])
def get_interface_ip(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
ip = socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15].encode()))[20:24])
except IOError:
ip = '0.0.0.0'
return ip
def arp_scan(interface):
mac = get_interface_mac(interface)
ip = get_interface_ip(interface)
ip_prefix = ip.rsplit('.', 1)[0] + '.'
cmd = 'arp-scan -I {} {} -B --retry=3'.format(interface, ip_prefix + '0/24')
output = os.popen(cmd).read()
pattern = re.compile(r'(\d+\.\d+\.\d+\.\d+)\s+([0-9a-fA-F:]+)')
result = []
for match in pattern.finditer(output):
if match.group(2) != mac:
result.append((match.group(1), match.group(2)))
return result
主程序
import time
import threading
import argparse
from arp_scan import arp_scan
class ArpDetector:
def __init__(self, interface):
self.interface = interface
self.ip_mac_dict = {}
self.attack_dict = {}
self.lock = threading.Lock()
def update_ip_mac_dict(self):
while True:
ip_mac_list = arp_scan(self.interface)
ip_mac_dict = dict(ip_mac_list)
with self.lock:
self.ip_mac_dict = ip_mac_dict
time.sleep(5)
def detect_arp_attack(self):
while True:
with self.lock:
ip_mac_dict = self.ip_mac_dict.copy()
for ip, mac in ip_mac_dict.items():
if ip not in self.attack_dict:
self.attack_dict[ip] = (mac, 0)
elif self.attack_dict[ip][0] != mac:
self.attack_dict[ip] = (mac, self.attack_dict[ip][1] + 1)
if self.attack_dict[ip][1] >= 3:
print('ARP attack detected: {} -> {}'.format(self.attack_dict[ip][0], ip))
time.sleep(1)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='ARP detector')
parser.add_argument('-i', '--interface', required=True, help='network interface name')
args = parser.parse_args()
arp_detector = ArpDetector(args.interface)
update_thread = threading.Thread(target=arp_detector.update_ip_mac_dict, daemon=True)
update_thread.start()
detect_thread = threading.Thread(target=arp_detector.detect_arp_attack, daemon=True)
detect_thread.start()
while True:
time.sleep(60)
使用方法
- 将代码保存到名为
arp_detector.py的文件中 - 在命令行中运行
python arp_detector.py -i eth0,其中eth0为网络接口名称
注意事项
- 确保系统已安装
arp-scan工具 - 软件需要管理员权限运行
- 为了提高检测效率,建议将
time.sleep(5)和time.sleep(1)的时间间隔调小
扩展功能
- 可以添加日志记录功能,将检测结果记录到文件中
- 可以添加报警功能,当检测到ARP攻击时,向用户发送邮件或短信提醒
- 可以添加防御功能,当检测到ARP攻击时,阻止攻击源的流量
总结
本软件提供了一种简单有效的ARP检测和防护方案,可以帮助用户识别和阻止ARP攻击。用户可以根据实际情况对软件进行调整和扩展,以满足不同的安全需求。
原文地址: https://www.cveoy.top/t/topic/jk12 著作权归作者所有。请勿转载和采集!