This example for you to share the Python port scan implementation code for your reference, the specific content as follows
To obtain the IP and port number for this computer:
Import Socket
def get_my_ip ():
try:
csock = Socket.socket (socket.af_inet, socket. SOCK_DGRAM)
csock.connect ((' 8.8.8.8 ', +))
(addr, port) = Csock.getsockname ()
csock.close ()
return Addr,port
except Socket.error: Return
"127.0.0.1"
def int_to_ip (int_ip): Return
Socket.inet_ntoa (Struct.pack (' I ', socket.htonl (INT_IP)
) def ip_to_int (IP): return
Socket.ntohl (Struct.unpack ("I", Socket.inet_aton (str (IP)) [0])
(ip,port) =get_ MY_IP ()
portscan.py
#!/usr/bin/python #-*-coding:utf-8-*-import optparse from socket import * from threading Import * Screenloc K = Semaphore (value=1) def connscan (Tgthost, tgtport): Try:connskt = socket (af_inet, sock_stream) connskt . Connect ((Tgthost, Tgtport)) connskt.send (' violentpython\r\n ') results = connskt.recv (MB) screenlock.acqui Re () print ' [+]%d/tcp open '% tgtport print ' [+] ' + str (results) Except:screenLock.acquire () PRI NT ' [-]%d/tcp closed '% tgtport finally:screenLock.release () connskt.close () def portscan (Tgthost, Tgtports
): Try:tgtip = gethostbyname (tgthost) Except:print "[-] cannot resolve '%s ': Unknown host"%tgthost return try:tgtname = gethostbyaddr (tgtip) print ' \n[+] Scan Results for: ' + tgtname[0] Except:p Rint ' \n[+] Scan Results for: ' + tgtip setdefaulttimeout (1) for tgtport in tgtports:t = Thread (Target=conns Can,args= (Tgthost,int (TGTport)) T.start () def main (): parser = Optparse. Optionparser (' Usage%prog ' +\ '-H <target host>-P <target port> ') parser.add_option ('-h ', dest= ' TgtHos T ', type= ' string ', \ help= ' Specify target host ') parser.add_option ('-P ', dest= ' tgtport ', type= ' string ', \ help= ' s Pecify Target Port[s] separated by comma ') (options, args) = Parser.parse_args () Tgthost = Options.tgthost TG Tports = str (options.tgtport). Split (', ') if (tgthost = None) |
(Tgtports[0] = None): Print Parser.usage exit (0) Portscan (tgthost, tgtports) If __name__ = ' __main__ ': Main ()
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.