Python script -- port scanner

Posted by facets on Sun, 06 Oct 2019 14:45:30 +0200

A simple port scanner written by python, Python environment 3.7.0, windows system

Scanning whether the specified port is open for a given host
TCP connection scanning uses three handshakes of TCP to determine whether the host port is open or not. After confirming that the host port is open, send a message to the port, receive the message returned by the port, and then judge the service that the port is running.
When used, the - H parameter can provide the domain name or ip address of the host, and - p/-P writes the ports to be scanned, with multiple ports separated by commas.

'''
@Author:yw
//Reference Book: python Skills: Using python to Become the Top ***.
'''
import optparse
from socket import *
import threading
threadlock = threading.Lock() #Instantiating threadlock objects

def Conn_scan(Host, Port):
    try:
        conn = socket(AF_INET,SOCK_STREAM)
        conn.connect((Host, Port))
        #conn.send('ywboy'.encode('utf-8')) #Send test
        #results = conn.recv(100)           #Receive the information returned by the host
        threadlock.acquire()                 #Lock up
        print("[+]%d/tcp Open" % Port)
        #print('[+]'+results.decode('utf-8'))
        conn.close()
    except Exception as e:
        threadlock.acquire()                 #Release lock
        print('[-]%d/Tcp Closed' % Port)
    finally:
        threadlock.release()
        conn.close()
def Port_scan(Host, Ports):
    try:
        IP = gethostbyname(Host)        ##Get the ip address of the corresponding host
    except:
        print("[-] Cannot resolve '%s':Unknow host" % Host)
        return
    try:
        Name = gethostbyaddr(Host)          ##Get the information of the corresponding host, return the host name, host alias list, host IP address list
        print("\n[+] Scan result for:"+Name[0])
    except:
        print("\n[+] Scan Results for:"+IP)
    setdefaulttimeout(1)
    for Port in Ports:
        print("Scan port:"+Port)
        Conn_scan(Host, int(Port))
def main():
    usage = "usage %prog -H <target Host> -p/-P <target ports>"
    parse = optparse.OptionParser(usage)
    parse.add_option('-H', dest='Host', type='string', help='target Host')
    parse.add_option('-p','-P', dest='Ports', type='string', help='SCan Port')
    (options, args) = parse.parse_args()
    Host = options.Host
    Ports = str(options.Ports).split(',')
    if (Host==None)|(Ports==None):
        print(parse.usage)
        exit(0)
    Port_scan(Host,Ports)
if __name__ == '__main__':
    main()

The above code, because I just did the port scan, so commented out the code to determine the port scan service.

Operation results:

Topics: Python socket Windows