基于python2.7的多线程端口扫描器
使用方法:
python2 scan.py -H www.baidu.com -p 80,443,3389
源代码:
# -*- coding: utf-8 -*- import optparse import socket from socket import * from threading import * screenLock = Semaphore(value=1) def connScan(tgtHost,tgtPort): #尝试逐个链接我们需要连接的端口 try: #第一个是网络的协议,第二个是默认的参数值 connSkt = socket(AF_INET,SOCK_STREAM) connSkt.connect((tgtHost,tgtPort)) connSkt.send('addslashes_J0NG ') results = connSkt.recv(100) screenLock.acquire() print '[+]%d/tcp open'% tgtPort print '[+]' +str(results) connSkt.close() except: screenLock.acquire() print '[-]%d/tcp closed'% tgtPort finally: screenLock.release() connSkt.close() def portScan(tgtHost,tgtPorts): try:#获得主机的ip地址 tgtIP = gethostbyname(tgtHost) except: print "[-] Cannot resolve '%s': Unknow 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 = Thread(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',dest = 'tgtHost',type = 'string',help = 'specif target host') parser.add_option('-p',dest = 'tgtPort',type = 'string',help = 'specif target port') (options,args) = parser.parse_args() tgtHost = options.tgtHost tgtPorts = str(options.tgtPort).split(',') if (tgtHost ==None) | (tgtPorts[0] == None): print '[-]you must specify a target host and port[s].' exit(0) portScan(tgtHost,tgtPorts) if __name__=="__main__": main()