#!/usr/bin/env python # -*- coding:UTF-8 -*- import optparse import socket import threading # 用法 python threadPortScan.py -H www.baidu.com -p 22 23 3306 3389 6437 445 443 7001 80 #构造一个方法 创建具有给定许可数的计数信号量并设置为非公平信号量,就是说创建一个阻塞对象 screenLock = threading.Semaphore(value=1) def connScan(tgtHost,tgtPort): try: #创建一个套接字对象 connSkt = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #尝试连接 connSkt.connect((tgtHost,tgtPort)) #发送数据 connSkt.send("violent pyhon ") #接受饭回来的数据 result = connSkt.recv(100) #产生的线程排好队,一个一个得打印 screenLock.acquire() print "[+]%d/tcp open" %tgtPort print "[+]" + str(result) except: print "[-]%d/tcp closed" %tgtPort finally: #释放掉 screenLock.release() #关闭连接 connSkt.close() def portScan(tgtHost,tgtPorts): try: #根据域名,获取ip tgtIP = socket.gethostbyname(tgtHost) except: print "[-]cannot resolve '%s':Unkonwn host" %tgtHost return try: tgtName = socket.gethostbyaddr(tgtIP) print " [+]Scan Result for:" + tgtName[0] except: print " [+]Scan Result for:" + tgtIP socket.setdefaulttimeout(1) for tgtPort in tgtPorts: print "Scanning port " + str(tgtPort) t = threading.Thread(target = connScan,args = (tgtHost,int(tgtPort))) t.start() def main(): parse = optparse.OptionParser('usage %prog -H <targethost> -p <targetport>') parse.add_option('-H',dest = 'tgtHost',type = 'string',help = 'specify target host') parse.add_option('-p',dest = 'tgtPort',type = 'int',help = 'specify target port') (option,args) = parse.parse_args() tgtHost = option.tgtHost tgtPort = option.tgtPort args.append(tgtPort) if(tgtPort == None) | (tgtHost == None): print parse.usage exit(0) portScan(tgtHost,args) if __name__ == '__main__': main()