利用Python实现自动化Nmap扫描
需要提前安装好Python第三方模块python-nmap.
1 import nmap 2 import sys 3 import optparse 4 5 6 class NmapScanner: 7 def __init__(self) -> None: 8 self.targets = self.get_params()[0] 9 self.port_range = self.get_params()[1] 10 self.scanner = nmap.PortScanner() 11 self.banner() 12 13 14 15 def banner(self): 16 banner= """ 17 ************************************************** 18 19 ********** NMAP Automation Tool by Jason Wong***** 20 21 ************************************************** 22 """ 23 print(banner) 24 25 def get_params(self): 26 parser = optparse.OptionParser("Usage: <Program> -t target -p ports") 27 parser.add_option('-t', '--target', dest='target', type='string', help="Specify target IP address or network") 28 parser.add_option('-p', '--ports', dest='ports', type='string', help='Specify port or ports range') 29 options, args = parser.parse_args() 30 if options.target is None or options.ports is None: 31 print(parser.usage) 32 sys.exit(0) 33 return options.target, options.ports 34 35 36 def run(self): 37 try: 38 results = self.scanner.scan(self.targets, self.port_range) 39 all_hosts = self.scanner.all_hosts() 40 for host in all_hosts: 41 print("Host %s scan results: "% host) 42 print("Host is %s" % results['scan'][host]['status']['state']) 43 if results['scan'][host]['status']['state'] == 'up': 44 tcp_status = results['scan'][host]['tcp'] 45 46 for k,v in tcp_status.items(): 47 print('\ttcp\t', k,'\t',v['product'], '\t', v['version']) 48 except Exception as e: 49 print(e) 50 sys.exit() 51 52 53 if __name__ == "__main__": 54 scanner = NmapScanner() 55 scanner.run()
运行结果如下所示:
STRIVE FOR PROGRESS,NOT FOR PERFECTION