python 探測端口
最近在学习网络安全课程,探测对方哪个端口开启是黑客攻击的第一步:
写了一段探测对方端口的代码
使用格式:python -H 目标IP地址 -P 目标端口列表
1 # coding=UTF-8 2 import socket 3 import optparse 4 import threading 5 screenLock = threading.Semaphore(value=1) 6 def connScan(tgtHost,tgtPort): 7 try: 8 connSkt = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 9 connSkt.connect((tgtHost,tgtPort)) 10 connSkt.send('ViolentPython\r\n') 11 results = connSkt.recv(100) 12 screenLock.acquire() 13 print('[+]%d/tcp open'%tgtPort) 14 print ('[+] '+str(results)) 15 16 except: 17 screenLock.acquire()#加锁 18 print ('[-]%d/tcp closed'%tgtPort) 19 finally: 20 screenLock.release() 21 connSkt.close() 22 23 24 def portScan(tgtHost,tgtPorts): 25 try: 26 tgtIP =socket.gethostbyname(tgtHost) 27 28 except: 29 print "[-]Cannot resolve '%s':Unknown host" % tgtHost 30 return 31 try: 32 tgtName = socket.gethostbyaddr(tgtIP) 33 print "\n[+] Scan Results for :"+ tgtName[0] 34 except: 35 print "\n[+] Scan Results for:" + tgtIP 36 socket.setdefaulttimeout(1) 37 38 for tgtPort in tgtPorts: 39 print "Scanning port"+ str(tgtPort) 40 t = threading.Thread(target=connScan,args=(tgtHost,int(tgtPort))) 41 t.start() 42 43 def main(): 44 parser = optparse.OptionParser('usage%prog -H<target host> -p <target port>') 45 parser.add_option('-H',dest='tgtHost',type='string',help='specify target host') 46 parser.add_option('-p',dest='tgtPort',type='int',help='specify target port') 47 (options,args)=parser.parse_args() 48 tgtHost = options.tgtHost 49 tgtPort = options.tgtPort 50 args.append(tgtPort) 51 if(tgtHost == None)|(tgtPort == None): 52 return('[-] You must specify a target host and port[s]!') 53 exit(0) 54 portScan(tgtHost,args) 55 56 57 if __name__ == '__main__': 58 main() 59
下一步,准备写成一个可用的界面应用程序。