port scanner python script

Python port scanner – raw code with explanation

If you ever find yourself without access to Nmap here is some quick python code for testing the up/down status of 1000 TCP ports on a target host. The code is explained at the bottom:

#!/usr/bin/python

import socket
from termcolor import colored

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1)

host = input(“Enter the target host: “)

def portscanner(port):
if sock.connect_ex((host,port)):
print(colored(“Port %d is closed” % (port), ‘red’))
else:
print(colored(“port %d is open” % (port), ‘green’))

for port in range(1,1000):
portscanner(port)

Explanation:

import socket
from termcolor import colored

These 2 libraries are responsible for creating the connection to the target and for allowing us to add colour to the output

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1)

Sets the connection to use IP4 and sets the timeout to 1 second so you don’t get stuck waiting for connection requests to time out

host = input(“Enter the target host: “)

This is the prompt which you see when you run the code, it adds the input to the ‘host’ variable

def portscanner(port):
if sock.connect_ex((host,port)):
print(colored(“Port %d is closed” % (port), ‘red’))
else:
print(colored(“port %d is open” % (port), ‘green’))

Here is the main function. Instead of testing for a successful connection it looks for a failure, if so it reports that the port is closed. If anything else comes back it assumes the port is open and reports that.

for port in range(1,1000):

Sets the script to scan ports 1- 1000, you can change this to specific numbers or increase the range up to 65535

Advertisement