TCP port scanner

Keywords: socket Python Session

A TCP port scanner based on Python 3

Principle: TCP connection with different ports means that the port is open if the connection is successful, and closed if the connection is not successful.

import socket
import re
import threading
import time
 
lock = threading.Lock()
threads = list()
ports_list = list()
 
 
def judge_hostname_or_ip(target_host):
    # Determine whether the domain name or IP address is entered
    result = re.match(
        r"^(\d|[1-9]\d|1\d\d|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(\d|[1-9]\d|1\d\d|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\."
        "(\d|[1-9]\d|1\d\d|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(\d|[1-9]\d|1\d\d|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$",
        target_host)
 
    if result:
        # print(result.group())
        return result.group()
    else:
        try:
            socket.setdefaulttimeout(1)
            IP = socket.gethostbyname(target_host)
            return IP
        except Exception as e:
            print("Please enter the web address correctly or ip address...", e)
            exit()
 
 
def parse_port(ports):
    """Linking connectors-The transmitted value resolves to the corresponding digital port range 1-65535"""
    if ports:
        try:
            res = re.match(r'(\d+)-(\d+)', ports)
            if res:
                if int(res.group(2)) > 65535:
                    print("Wrong end port input!!....Please input new")
                    exit()
                return range(int(res.group(1)), int(res.group(2)))
        except:
            print("Port resolution error.....Please input the port range correctly")
            exit()
    else:
        return [19, 21, 22, 23, 25, 31, 42, 53, 67, 69, 79, 80, 88, 99, 102, 110, 113, 119, 220, 443]
 
 
def test_port(host, port):
    """Test whether the port is open"""
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((host, port))
        lock.acquire()   # Wire lock
        print("{}, {}Port open".format(host, port))
        ports_list.append(port)
    except:
        lock.acquire()
    finally:
        lock.release()
        s.close()
 
 
def main():
    ip = judge_hostname_or_ip(input("Please enter a domain name or IP:"))
    l = parse_port(input("Please enter the port range as follows: 1-1024 [Do not enter the Default scan common port for direct return]:"))
 
    t1 = time.time()
    # Maximum timeout per socket
    socket.setdefaulttimeout(3)
    # Open thread to test
    for port in l:
        t = threading.Thread(target=test_port, args=(ip, port))
        threads.append(t)    # Add to waiting thread list
        t.start()
 
    for t in threads:
        t.join()    # Wait for all threads to finish executing
 
    t2 = time.time()
    print("Total time consuming:", t2 - t1)
    print("IP:{}, Yes{},common{}End ports open".format(ip, ports_list, len(ports_list)))
 
 
if __name__ == '__main__':
    main()

2: TCP related knowledge

1. TCP connect scan: also known as full connection scan, this way is directly connected to the target port and completes the process of TCP three-time handshake. The scan result is relatively accurate, but the speed is relatively slow and can be easily detected by the target system.

2. TCP SYN scan: also known as semi open scan, this mode will send a SYN packet, start a TCP session, and wait for the target response packet. If an RST packet is received, the port is closed, and if a SYN/ACK packet is received, the corresponding port is open.

3. Tcp FIN scan: this method sends a FIN packet indicating that an active TCP connection is removed and the other party closes the connection. If an RST packet is received, the corresponding port is closed.

4. TCP XMAS scan: this method sends packets with PSH, FIN, URG, and TCP flags set to 1. If an RST packet is received, the corresponding port is closed

Reference article: https://blog.csdn.net/wgpython/article/details/79439830

Posted by om.bitsian on Tue, 31 Dec 2019 11:48:12 -0800