利用Python实现ARP欺骗检测工具

 

from scapy.all import *
import sys
import optparse
import termcolor

class ARPSpoofDetector:
    def __init__(self):
        self.interface = self.get_params()

    def get_params(self):
        parser = optparse.OptionParser('Usage: < Program >  -i interface')
        parser.add_option('-i', '--interface', dest='interface', type='string', help='Specify interface to listen')
        options, args = parser.parse_args()
        if options.interface is None:
            print(parser.usage)
            sys.exit()
        return options.interface    
    
        
    def get_mac_address(self, ip):
        try:
            packet = Ether(dst='ff:ff:ff:ff:ff:ff')/ARP(pdst=ip, op=1)
            ans,unans = srp(packet, timeout=2, verbose=False)
            if ans:
                mac_address =  ans.res[0][1].hwsrc
                return mac_address
            else:
                return None
        except Exception as e:
            print(e)
            sys.exit(0)
    
    def packet_handler(self,pkt):
        if pkt.haslayer(ARP) and pkt.getlayer(ARP).op == 2:
            sender_real_mac = self.get_mac_address(pkt.getlayer(ARP).psrc)
            captured_mac = pkt.getlayer(ARP).hwsrc
            if sender_real_mac != captured_mac:
                print(termcolor.colored("[-] Under attack", 'red'))
    
    def run(self):
        try:
            sniff(iface=self.interface, prn=self.packet_handler, store=False)
        
        except KeyboardInterrupt:
            print("[-] Exit program now")
            sys.exit()        

        except  Exception as e:
            print(e)
            sys.exit()
    

if __name__ == '__main__':
    arpspoofdetect = ARPSpoofDetector()
    arpspoofdetect.run()

 

posted @ 2022-06-09 09:04  Jason_huawen  阅读(170)  评论(0编辑  收藏  举报