Python write port scanner

Common ports:

portservice
twenty oneThe default is the ftp port, which mainly depends on whether to support anonymity, or you can run weak passwords
twenty twoThe default is shh port
twenty threeThe default is the telnet port
25The default is smtp service
53The default is DNS
123NTP
161, 162, 8161snmp service (SNMP open with 8161 IBM products)
389ldap group
80http service
443https service
512, 513rlogin service or exec
873rsync mainly depends on whether it supports anonymity, and can also run 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 possible to roam the intranet directly
3306mysql database
4899R-admin connection terminal
4440rundeck refer to WooYun: successfully roaming Sina intranet by borrowing a certain service from Sina
8834nessus service
4848glashfish
3311,3312kangle host management system
3389Remote login
5672rabbitMQ
5900VNC
6082Varnish refer to WooYun: Unauthorized access to Varnish HTTP accelerator CLI can easily lead to direct tampering of the website or entering the intranet as a proxy
6379Redis is generally not authenticated and can be accessed directly
7001weblogic
8080tomcat
8089jboss
8161activeMQ
8649Ganglia cluster system monitoring software
9000fastcgi service
9090IBM service
9200, 9300Elasticsearch Reference WooYun: Play more with ElasticSearch command execution vulnerability in a certain server
9999amg encrypted version
10050zabbix
11211Unauthorized access to memcache
27017, 28017Unauthorized access to mongodb, login 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, first import the socket module::
socket.gethostbyname(hostname)change the host name to an IP address
socket.gethostbyaddr(ip_address);: pass in an IP address and return a tuple containing the host name, alias list and A list of IP addresses of the same interface
socket.socket([family[,type[,proto]]]);: A new socket will be generated through the given 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 The word is SOCK_STREAM (default), or UDP socket is SOCK_DGRAM, or other socket types. The last protocol number is usually zero, and it is omitted in most cases.
socket.connect(address): Connect to the socket at address. Generally, the format of address is a tuple (hostname, port). If there is a connection error, socket.error will be returned.
socket.connect_ex(adddress): The function is the same as connect(address), but it returns 0 if it succeeds, and returns the value of error if it fails.

The first step is to enter the target host name and the list of ports to be scanned. Then get the target's network IP address through the target host name. Use each port in the list to get the connection destination address, and finally determine the special service running on the port. Finally, specific data will be sent and the identifier returned by the specific application will be read. After confirming the help information, you need to make a socket connection to the specific port and the host, and finally check the port connection status. Use multi-threading to increase speed.

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

screenLock = threading.Semaphore(value=1)


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


def portScan(tgtHost, tgtPorts):
    try:
        tgtIP = socket.gethostbyname(tgtHost)
    except Exception as e:
        print("[-] Cannot resolve '%s':Unknown host" % tgtHost)
        return
    # try:
    # tgtName = socket.gethostbyaddr(tgtIP)
    # print('\n[+]Scan Results for '+tgtName[0])
    # except:
    print('\n[+] Scan Results for ' + tgtIP)
    socket.setdefaulttimeout(1)
    for tgtPort in tgtPorts:
        # print('[+] Scaningport' + str(tgtPort))
        t = threading.Thread(target=connScan, args=(tgtHost, int(tgtPort)))
        t.start()
        # 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):
            args.append(i)
    else:
        args.append(int(tgtPort))
    if (tgtHost == None) | (tgtPort == None):
        print('[-] You must specify a target host and port[s]!')
        exit(0)
    portScan(tgtHost, args)


if __name__ == '__main__':
    main()

Comparison of running results with masscan:

Insert picture description here


Insert picture description here