Python port scanner

Common ports:

21The default is ftp port, which mainly depends on whether anonymous is supported or weak password can be used
22The default is shh port
23The default is telnet port
25The default is smtp service
53The default is DNS
161,162,8161SNMP service (8161 SNMP opened by IBM)
389ldap community
80http service
443https service
512,513rlogin service or exec
873rsync mainly depends on whether it supports anonymity or weak passwords
1433mssql database
1080socks proxy
1521oracle Database
1900bes default background
2049nfs service
2601,2604Zebra routing, default password zebra
2028,2083cpanel host management system
3128,3312squid proxy default port. If no password is set, it is likely to roam the intranet directly
3306mysql database
4899R-admin connection end
4440rundeck reference WooYun: successfully roaming Sina intranet by borrowing a service from Sina
8834nessus service
3311,3312kangle host management system
3389Remote login
6082Access to the intranet directly by wonivar cli without authorization
6379redis generally has no authentication and can be accessed directly
8649ganglia cluster system monitoring software
9000fastcgi service
9090IBM services
9200,9300ElasticSearch reference WooYun: play more ElasticSearch Command Execution Vulnerability of a server
9999amg encrypted version
11211memcache unauthorized access
27017,28017mongodb is not authorized to access and logs in without password by default
3777Dahua monitoring equipment
50000sap netweaver remote command execution vulnerability

Write your own TCP port scanner, use TCP full connection scanning to identify the host, and first import the socket module:
socket.gethostbyname(hostname): change the host name to the IP address;
socket.gethostbyaddr(ip_address): pass in an IP address and return a tuple, including host name, alias list and IP address list of the same interface;
socket.socket([family[,type[,proto]]]): a new socket will be generated. Given the socket address cluster and socket type, the address cluster can be AF_ INET (default), AF_INET6 or AF_UNIX. In addition, the socket type can be a TCP socket, that is, sock_ Stream (default), or UDP socket, i.e. SOCK_DGRAM, or other socket type. Finally, the agreement number is usually zero, which is omitted in most cases.
socket.connect(address): connect to the socket at address. Generally, the format of address is tuple (hostname,port). If there is a connection error, socket is returned Error error.
socket.connect_ex(adddress): the function is the same as that of connect(address), but 0 is returned for success and error is returned for failure.

The first step is to enter the target host name and the list of ports to scan. Then get the network IP address of the target through the target host name. Use each port in the list to get the connection target address, and finally determine the special services running on the port. Finally, the specific data will be sent and the identification returned by the specific application will be read. After the help information is determined, you need to socket connect the specific port to the host, and finally check the port connection status. Use multithreading to improve speed.

The source code is as follows
import optparse
import socket
import threading
import re

screenLock = threading.Semaphore(value=1)

def connScan(tgtHost, tgtPort):
        connSkt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = connSkt.connect_ex((tgtHost, tgtPort))
        # connSkt.send(b'test')
        # results = connSkt.recv(100)
        if (result == 0):
            print('[+] {0}:{1} /tcp open'.format(tgtHost, tgtPort))
        # else:
        #     print('[-] %d/tcp closed' % tgtPort)
        # print('[-] ' + str(results))
        # connSkt.close()
        print('[-] error')

def portScan(tgtHost, tgtPorts):
        tgtIP = socket.gethostbyname(tgtHost)
    except Exception as e:
        print("[-] Cannot resolve '%s':Unknown host" % tgtHost)
    # try:
    # tgtName = socket.gethostbyaddr(tgtIP)
    # print('\n[+]Scan Results for '+tgtName[0])
    # except:
    print('\n[+] Scan Results for ' + tgtIP)
    for tgtPort in tgtPorts:
        # print('[+] Scaningport' + str(tgtPort))
        t = threading.Thread(target=connScan, args=(tgtHost, int(tgtPort)))
        # connScan(tgtHost,int(tgtPort))

def main():
    parser = optparse.OptionParser('usage %prog -H <target host> -p <target port>')
    parser.add_option('-H', dest='tgtHost', type='string', help='specify target host')
    parser.add_option('-p', dest='tgtPort', type='string', help='specify target port')
    (options, args) = parser.parse_args()
    tgtHost = options.tgtHost
    tgtPort = options.tgtPort
    if '-' in tgtPort:
        Ports = re.findall(r'[0-9]{1,5}', tgtPort)
        first = int(Ports[0])
        last = int(Ports[1])
        for i in range(first, last + 1):
    if (tgtHost == None) | (tgtPort == None):
        print('[-] You must specify a target host and port[s]!')
    portScan(tgtHost, args)

if __name__ == '__main__':

Comparison between operation results and masscan:

Keywords: Python penetration test

Added by dull1554 on Tue, 08 Feb 2022 06:27:59 +0200