Recently i need port scanner code for one of Python script in which i was trying to configure some application, during configuration i like to check if port i free or already in listening mode, So if port is listening mode we can try to configure it on another port.
During this automation project , i tried to write small code for port scanner which after small modification could act as good TCP port scanner for any remote host.

SetUP

I am using python 3.7 for writing this code.

# /data/conda/bin/python -V
Python 3.7.4

Portscanner code

I used socket module to write this port scanner code, which is like below.

import socket
def pscan(host,port_num):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((host, int(port_num)))
        s.shutdown(socket.SHUT_RDWR)
        return True
    except:
        return False
    finally:
        s.close()

Above code is bundle in one function just to make it use anywhere in script or re-usable during testing purpose as well.We can use this function like below.

>>> import socket
>>> def pscan(host,port_num):
...     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
...     try:
...         s.connect((host, int(port_num)))
...         s.shutdown(socket.SHUT_RDWR)
...         return True
...     except:
...         return False
...     finally:
...         s.close()
... 
>>> for i in range(1,9999):
...     if pscan("192.168.0.12",i):
...             print(f'{i} is open')
... 
21 is open
22 is open
111 is open
2049 is open
3389 is open
5000 is open

So above we tried to scan all TCP port between 1-9999 for host (192.168.0.12), which has some ports open during this testing. We can try this code as port scanner, it’s even quit fast to work on such large number of ports in once.