利用 python-nmap模块进行端口扫描,简单的实现方式
实现了三种输入方式
1)单个端口扫描,例如 python scanport.py -H host -P port 2)多个端口扫描,例如 python scanport.py -H host -P port1,port2,..... 3)连续端口扫描,例如 python scanport.py -H host -P start_port-end_port
#coding:utf-8import nmapimport optparseimport sysclass INFO: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' ARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m'def scanport(host, port): nm =nmap.PortScanner() try: result = nm.scan(host,port) state = result['scan'][host]['tcp'][int(port)]['state']# 多层字典嵌套取值 if state =='open': print INFO.OKBLUE+'[*] '+host+ ' tcp/'+port+" "+state+INFO.ENDC else: print INFO.WARNING+'[*] '+host+ ' tcp/'+port+" "+state+INFO.ENDC except Exception,e: raise eif __name__ == '__main__': parser = optparse.OptionParser("usage %prog -H-p or -p - ") parser.add_option('-H', dest='Host', type='string', help='specify target host') parser.add_option('-P', dest='Port', type='string', help='specify target port[s] separated by "-"'or ",") (options, args) = parser.parse_args() if options.Host ==None or options.Port==None: print parser.usage sys.exit() host = options.Host ports = options.Port print host,ports #如果是连续的端口 if '-' in ports: ports_list = ports.split('-') for p in range(int(ports_list[0]),int(ports_list[1])+1): scanport(host, str(p)) #其他的情况 else: ports_list = ports.split(',') for p in ports_list: scanport(host, p)
上面的代码有点复杂,改良之后的代码如下:
优化结构import nmap,argparse, sysclass INFO: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' ARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def scan_port(host, port): nm = nmap.PortScanner() try: result= nm.scan(host,port) print result state = result['scan'][host]['tcp'][int(port)]['state'] if state == 'open': print INFO.OKBLUE+'[*] '+host+ ' tcp/'+port+" "+state+INFO.ENDC else: print INFO.WARNING + '[*] ' + host + ' tcp/' + port + " " + state + INFO.ENDC except Exception,e: raise edef get_args(): parger = argparse.ArgumentParser(description='port scan script') parger.add_argument('-H', '--host', help='specify target host') parger.add_argument('-P', '--port', help='specify target port') args = parger.parse_args() print args if args.host == None: parger.error('host is required') sys.exit() if args.port == None: parger.error('host is required') sys.exit() else: return args def main(): args = get_args() if '-' in args.port: ports_list = args.port.split('-') for p in range(int(ports_list[0]),int(ports_list[1])+1): scan_port(args.host, str(p)) else: ports_list = args.port.split(',') for p in ports_list: scan_port(args.host, p) if __name__ == '__main__': main()