import sys
import socket
import pyfiglet
ascii_banner = pyfiglet.figlet_format("TryHackMe \n Python 4 Pentesters \nPort Scanner")
print(ascii_banner)
ip = '192.168.1.6'
open_ports =[]
ports = range(1, 65535)
def probe_port(ip, port, result = 1):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.5)
r = sock.connect_ex((ip, port))
if r == 0:
result = r
sock.close()
except Exception as e:
pass
return result
for port in ports:
sys.stdout.flush()
response = probe_port(ip, port)
if response == 0:
open_ports.append(port)
if open_ports:
print ("Open Ports are: ")
print (sorted(open_ports))
else:
print ("Looks like no ports are open :(")To better understand the port scanning process, we can break down the code into several sections:
Importing modules that will help the code run:
import sysimport socketModules could also be imported with a single line using
import socket,sys**
Specifying the target:**
ip = '192.168.1.6' **
An empty “open_ports” array that will be populated later with the detected open ports:
**
open_ports =[] **
Ports that will be probed:**
ports = range(1, 65535)For this example, we have chosen to scan all TCP ports using the range() function. However, if you are looking for a specific service or want to save time by scanning a few common ports, the code could be changed as follows;
ports = { 21, 22, 23, 53, 80, 135, 443, 445}The list above is relatively small. As we are trying to keep a rather low profile, we have limited the list to ports that will likely be used by systems connected to a corporate network.Getting the IP address of the domain name given as target. The code also works if the user directly provides the IP address.
ip = socket.gethostbyname(host)Tries to connect to the port:

This code is followed by a for loop that iterates through the specified port list:

Below are the results of the port scanning script run against a random target.
**
**