Simple Port Scanner using Python

Omer Gunesacar
4 min readMar 13, 2023

--

Code : https://github.com/OmerGnscr/Simple-Port-Scanner

Basic Port Scanner that scans the given port for the given target and lists open ports, shows the status and which service is running on that port.

First, let’s take a look at the code and then, break it down into the pieces to analyze it.

import socket
import sys
from datetime import datetime
import os

start_time = datetime.now()

ip = socket.gethostbyname(sys.argv[1])

ping = os.system("ping {} -c 1 > /dev/null".format(ip))

print("-"*51)
print("[+] Target: ", sys.argv[1])
print("[+] Ports: ", sys.argv[2])

if ping == 0:
print("[+] {} is up and running".format(sys.argv[1]))
else:
print("[+] {} is down".format(sys.argv[1]))
print("Exiting...")
exit()

print("[+] Scanning started at: {}".format(start_time))
print("-"*51)

def scan_specific_ports():
ports = sys.argv[2]
ports = ports.split(',')

for i in ports:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((ip, int(i)))
try:
service = socket.getservbyport(int(i))
except:
service = "None"

if (result == 0):
print(" Port: {}\t State: Open\t Service: {}".format(i, service))
elif (result == 110):
print(" Port: {}\t State: Filtered\t Service: {}".format(i, service))
else:
print(" Port: {}\t State: Closed\t Service: {}".format(i, service))

sock.close()

print("-"*51)
time_passed = datetime.now() - start_time
print("Scanning is completed in", time_passed)

def scan_multiple_ports():
start_port = int(sys.argv[2])
end_port = int(sys.argv[3])

if start_port > end_port:
tmp = start_port
start_port = end_port
end_port = tmp

for ports in range(start_port,end_port+1):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((ip, ports))
try:
service = socket.getservbyport(int(i))
except:
service = "None"

if (result == 0):
print(" Port: {}\t State: Open\t Service: {}".format(ports, service))
elif (result == 110):
print(" Port: {}\t State: Filtered\t Service: {}".format(ports, service))
else:
print(" Port: {}\t State: Closed\t Service: {}".format(ports, service))

sock.close()

print("-"*51)
time_passed = datetime.now() - start_time
print("Scannig is completed in", time_passed)

if __name__ == "__main__":
try:
if (len(sys.argv) == 3):
scan_specific_ports()
elif (len(sys.argv) == 4):
scan_multiple_ports()
else:
print("Invalid number of arguments")
print("Usage: python3 portscanner <IP> <START_PORT> <END_PORT>")
print("Usage: python3 portscanner <IP> <PORT1,PORT2,...>")

except KeyboardInterrupt:
print("\nExiting...")

except OverflowError:
print("\nPort must be 0-65535.")

import socket: Is used for communication between us and the target.
import sys: Is used for be able to use command line arguments. (argv)
import datetime: Is used to compute time spent on scanning.
import os: Is used for executing the command ping.

start_time = datetime.now() is used to get current time and date to calculate time spent on scanning.

ip = socket.gethostbyname(sys.argv[1]) returns the IP address of a given host name.

ping = os.system(“ping {} -c 1 > /dev/null”.format(ip)) is used to execute the ping command to see if the host is up or down. (/dev/null discard anything written to it, they go to valhalla)

print("-"*51)
print("[+] Target: ", sys.argv[1])
print("[+] Ports: ", sys.argv[2])

if ping == 0:
print("[+] {} is up and running".format(sys.argv[1]))
else:
print("[+] {} is down".format(sys.argv[1]))
print("Exiting...")
exit()

print("[+] Scanning started at: {}".format(start_time))
print("-"*51)

This part is for just information like what the target is, what the ports are and time that scanning started. If the target is down, program just exits.

def scan_specific_ports():
ports = sys.argv[2]
ports = ports.split(',')

for i in ports:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((ip, int(i)))
try:
service = socket.getservbyport(int(i))
except:
service = "None"

if (result == 0):
print(" Port: {}\t State: Open\t Service: {}".format(i, service))
elif (result == 110):
print(" Port: {}\t State: Filtered\t Service: {}".format(i, service))
else:
print(" Port: {}\t State: Closed\t Service: {}".format(i, service))

sock.close()

scan_specific_ports function is used to scan all the given ports by one by on the given target. I defined a variable called “ports” and assign it to argv[2] value which we use for specifying the ports.
AF_INET stands for address family and is used to make our socket communicate with the given port on a given address.
SOCK_STREAM is the socket type for TCP.
connect_ex() is used to connect to a socket at given address. It returns 0 if the port is open, returns 110 if port is filtered and returns 111 if closed.
getservbyport() is used to get service name like ssh, http or https.
close() closes the connection

def scan_multiple_ports():
start_port = int(sys.argv[2])
end_port = int(sys.argv[3])

if start_port > end_port:
tmp = start_port
start_port = end_port
end_port = tmp

for ports in range(start_port,end_port+1):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((ip, ports))
try:
service = socket.getservbyport(int(i))
except:
service = "None"

if (result == 0):
print(" Port: {}\t State: Open\t Service: {}".format(ports, service))
elif (result == 110):
print(" Port: {}\t State: Filtered\t Service: {}".format(ports, service))
else:
print(" Port: {}\t State: Closed\t Service: {}".format(ports, service))

sock.close()

It is just like an scan_specific_ports function with a difference of scanning an specific range of ports.
If a user sets the start_port is greater then end_port, that 4 lines of code swaps the values.

if __name__ == "__main__":
try:
if (len(sys.argv) == 3):
scan_specific_ports()
elif (len(sys.argv) == 4):
scan_multiple_ports()
else:
print("Invalid number of arguments")
print("Usage: python3 portscanner <IP> <START_PORT> <END_PORT>")
print("Usage: python3 portscanner <IP> <PORT1,PORT2,...>")

except KeyboardInterrupt:
print("\nExiting...")

except OverflowError:
print("\nPort must be 0-65535.")

If a command line argument is equal to 3, scan_specific_ports() function executes,
if length of argv is equal to 4, scan_multiple_ports() executes.

An example of the Port Scanner

--

--

Omer Gunesacar
Omer Gunesacar

Written by Omer Gunesacar

EE Engineer interested in Cyber Security.

Responses (1)