利用Python实现类似于Kali Linux中NetDiscover工具的代码
本代码一定要实现多线程模块或者多进程模块,否则扫描网络会非常慢,慢的难以忍受。
为了实现自动化,本地网络的前缀通过subprocess模块提取命令执行结果而得到,然后通过循环,即可以得到网络中具体的每个IP地址。
from scapy.all import * import subprocess import optparse import sys import termcolor import threading class NetDiscover: def __init__(self) -> None: self.interface = self.get_params() #接口名称,通过命令行处理而得到 self.banner() def get_params(self): parser = optparse.OptionParser('Usage: <Program> -i interface') parser.add_option('-i', '--interface', dest='interface', type='string', help='Specify interface to scan') options, args = parser.parse_args() if options.interface is None: print(parser.usage) sys.exit(0) return options.interface def banner(self): banner = """ ****************************************************************** ****************************************************************** %s ****************************************************************** ****************************************************************** """ % termcolor.colored("NetDiscover Tool by Jason Wong V1.0",'yellow') print(banner) def get_prefix(self):
"""通过本方法获得接口所在网络的前缀地址""" try: command = "ifconfig %s | grep 'inet ' | awk '{print $2}'" % self.interface result = subprocess.check_output(command,shell=True).decode('utf-8').strip() ip_element_list = result.split('.') network_prefix = ip_element_list[0] + '.' + ip_element_list[1] + '.' + ip_element_list[2] + '.' return network_prefix except: print("Failed to get network prefix") sys.exit(0) def get_host_info(self, ip): packet = Ether(dst='ff:ff:ff:ff:ff:ff')/ARP(op=1,pdst=ip) try: res = srp(packet,timeout=1,verbose=False) if res[0].res: mac_address = res[0].res[0][1].hwsrc print("\t %s\t\t%s\t\tUP" %(ip, mac_address)) except: pass def run(self): prefix = self.get_prefix() print("\tIP \t\t\tMAC_Address\t\t\tStatus") for i in range(255): ip_addr = prefix + str(i) t = threading.Thread(target=self.get_host_info, args=(ip_addr,)) t.start() if __name__ == "__main__": net_discover = NetDiscover() net_discover.run()
运行效果如下图所示:
STRIVE FOR PROGRESS,NOT FOR PERFECTION