Build a Python TCP Port Scanner with Multithreading and Nmap

This article demonstrates how to build a Python TCP port scanner using raw sockets, adds service fingerprinting by sending probes, speeds up scans with multithreading, and shows an alternative approach using the nmap library, complete with example code and sample output.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Build a Python TCP Port Scanner with Multithreading and Nmap

First we need to scan a host's ports to see which are open.

Scanning Open Ports

# Test if the current host and port are open using a direct socket connection
def connScan(host, port):
    try:
        connSkt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        connSkt.connect((host, port))
        print("tcp open port:" + str(port))
    except:
        print('tcp closed:' + str(port))

def portScan(tgtHost, tgtPorts):
    try:
        tgtIP = socket.gethostbyname(tgtHost)
    except:
        print("[-] Cannot resolve '%s': Unknown host" % tgtHost)
        return
    try:
        tgtName = socket.gethostbyaddr(tgtIP)
        print('
[+] Scan Results for: ' + tgtName[0])
    except:
        print('
[+] Scan Results for: ' + tgtIP)
    socket.setdefaulttimeout(1)
    for tgtPort in tgtPorts:
        print('Scanning port ' + str(tgtPort))
        connScan(tgtHost, int(tgtPort))

Example call scanning common ports on www.baidu.com.

portScan('www.baidu.com', [80, 443, 3389, 1433, 23, 445])

Scanning Baidu's Ports

Output shows which ports are open or closed, e.g., tcp open port:80, tcp closed:3389, etc.

Capturing Application Fingerprints

To identify services, send a probe string after establishing a connection and read the response.

# Test if the current host and port are open, then send a probe and read response
def connScan(host, port):
    try:
        connSkt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        connSkt.connect((host, port))
        connSkt.send('Python
')
        results = connSkt.recv(100)
        print("tcp open port:" + str(port))
        print('[+] ' + str(results))
    except:
        print('tcp closed:' + str(port))

def portScan(tgtHost, tgtPorts):
    try:
        tgtIP = socket.gethostbyname(tgtHost)
    except:
        print("[-] Cannot resolve '%s': Unknown host" % tgtHost)
        return
    try:
        tgtName = socket.gethostbyaddr(tgtIP)
        print('
[+] Scan Results for: ' + tgtName[0])
    except:
        print('
[+] Scan Results for: ' + tgtIP)
    socket.setdefaulttimeout(1)
    for tgtPort in tgtPorts:
        print('Scanning port ' + str(tgtPort))
        connScan(tgtHost, int(tgtPort))

portScan('www.qq.com', [22, 80, 443, 3389, 1433, 23, 445])

Multithreaded Scanning

Using Python threads to scan ports concurrently reduces overall scan time.

for tgtPort in tgtPorts:
    print('Scanning port ' + str(tgtPort))
    t = threading.Thread(target=connScan, args=(tgtHost, int(tgtPort)))
    t.start()

Using nmap

The nmap Python library can perform the same scan with higher‑level functionality.

import nmap

def nmapScan(tgtHost, tgtPort):
    nmScan = nmap.PortScanner()
    results = nmScan.scan(tgtHost, tgtPort)
    state = results['scan'][tgtHost]['tcp'][int(tgtPort)]['state']
    print(" [*] " + tgtHost + " tcp/" + tgtPort + " " + state)

nmapScan('10.108.x.x', '8080')
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

multithreadingsocket programmingport scanningnmap
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.