import tkinter as tk
import os
import sys
import time
import threading
import netifaces
from scapy.all import *


class ArpDetector:
    def __init__(self, interface):
        self.interface = interface
        self.ip_mac_map = {}
        self.attacker_ip = None
        self.attacker_mac = None
        self.thread = None
        self.stop_event = threading.Event()

    def start(self):
        self.thread = threading.Thread(target=self.run)
        self.thread.start()

    def stop(self):
        self.stop_event.set()
        self.thread.join()

    def run(self):
        self.attacker_ip = netifaces.ifaddresses(self.interface)[netifaces.AF_INET][0]['addr']
        self.attacker_mac = get_mac_by_ip(self.attacker_ip) # 修改获取MAC地址的方式
        print(f'Attacker IP: {self.attacker_ip}, MAC: {self.attacker_mac}')

        while not self.stop_event.is_set():
            self.scan_network()
            self.detect_arp_spoofing()
            time.sleep(5)

    def scan_network(self):
        for ip in netifaces.ifaddresses(self.interface)[netifaces.AF_INET][0]['addr'].split('.')[:-1]:
            for i in range(1, 255):
                target_ip = f'{ip}.{i}'
                if target_ip != self.attacker_ip:
                    arp_request = ARP(pdst=target_ip)
                    arp_reply = sr1(arp_request, timeout=1, verbose=0)
                    if arp_reply and arp_reply.hwsrc not in ('00:00:00:00:00:00', self.attacker_mac):
                        self.ip_mac_map[target_ip] = arp_reply.hwsrc

    def detect_arp_spoofing(self):
        for target_ip, target_mac in self.ip_mac_map.items():
            arp_request = ARP(op=1, pdst=target_ip, hwdst=target_mac, psrc=self.attacker_ip, hwsrc=self.attacker_mac)
            arp_reply = sr1(arp_request, timeout=1, verbose=0)
            if arp_reply and arp_reply.hwsrc != target_mac:
                print(f'ARP spoofing detected: {target_ip} ({target_mac}) -> {arp_reply.hwsrc}')

# ...  其他类定义 ...

if __name__ == '__main__':
    login_window = LoginWindow()
    main_window = MainWindow()

代码说明:

  • 导入get_mac_by_ip函数:scapy.layers.l2模块导入get_mac_by_ip函数,用于根据IP地址获取MAC地址。
  • 使用get_mac_by_ip函数:ArpDetector类的run方法中,使用get_mac_by_ip(self.attacker_ip)获取攻击者的MAC地址。

其他优化建议:

  • 添加注释: 为代码添加清晰的注释,解释代码的功能和逻辑。
  • 错误处理: 添加错误处理机制,例如捕获异常并记录错误信息。
  • 用户界面: 优化用户界面,使其更加友好和易用。
  • 代码结构: 优化代码结构,例如将不同的功能模块封装成函数或类。

通过以上优化,可以提高代码的可读性、可维护性和安全性,并使其更易于被搜索引擎收录。

Python网络安全工具:ARP欺骗、ICMP洪水和TCP攻击检测

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

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