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)
``
基于Linux的Python实现ARP检测防护软件设计模块包含能够获取局域网活动主机的MAC地址、IP地址能够检测防护ARP攻击行为并记录保存能够显示出ARP攻击源的MAC地址、IP地址。请用代码详细写出需要调用的py文件代码详细写出主程序的py文件代码详细写出arp_scanpy文件

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

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