多线程版
import optparse import socket from socket import * def connScan(tgtHost,tgtPort): try: connSkt=socket(AF_INET,SOCK_STREAM) connskt.connect(tgtHost,tgtPort) connSkt.send('Violenpython ') results=connSkt.recv(100) screenlock.acquire() print('[+] %d/tcp open' %tgtPort) print('[+]'+ str(results)) #connSkt.close() except: screenlock.qcquire() print('[+] %d/tcp close' % tgtPort) finally: screenlock.acquire() connSkt.close() def portScan(tgtHost,tgtPorts): try: tgtip=gethostbyname(tgthost) except: print("[-] cannot resolve '%s' : unknown host" %tgtHost) return try: tgtname=gethostbyaddr(tgtip) print(' [+] scan results for: '+tgtname[0]) except: print(' [+] scan results for:'+tgtip) setdefaulttimeout(1) for tgtPort in tgtPorts: t=thrad(target=connScan,args=(tgthost,int(tgtPort))) t.start() def main(): parser=optparse.OptionParser('"usage%prog "+ "-H<target host> -p <target port>"') parser.add_option('-H',des='tgthost',type='string', help ='specify target host') parser.add_option('-P',des='tgtport',type='string', help ='specify target port[s] separated by comma') (options,args)=parser.parse_args() tgthost=options.tgthost tgtports=str(options.tgtport).split(',') if (tgthost==None)| (tgtports[0]==None): print(parser.usage) exit(0) portScan(tgthost,tgtports) if __name__=='_main__': main()
nmap版
# coding=UTF-8 import optparse import nmap def nmapScan(tgtHost, tgtPort): nmScan = nmap.PortScanner() results = nmScan.scan(tgtHost, tgtPort) state = results['scan'][tgtHost]['tcp'][int(tgtPort)]['state'] print(" [*] " + tgtHost + " tcp/" + tgtPort + " " + state) def main(): parser = optparse.OptionParser('usage%prog –H <target host> -p <target port>') parser.add_option('-H', dest='tgtHost',type='string', help='specify target host') parser.add_option('-p', dest='tgtPort', type='string', help='specify target port') (options, args)=parser.parse_args() tgtHost = options.tgtHost tgtPort = options.tgtPort args.append(tgtPort) if (tgtHost == None) | (tgtPort == None): print('[-] You must specify a target host and port[s]!') exit(0) for tgport in args: nmapScan(tgtHost, tgport) if __name__ == '__main__': main()