Using List for Port Scan in Python: Hacking with Python Series

The below program makes use of Lists in python to define different ports. It takes this list and then passes it to a scan function which checks if the port is open. This is a basic program. I have written this to show you the usage of list with port numbers. This script do not grab banner.

Let’s get on the code:

Explanation:

portnum=[21,22,23,25,80,8080] : This is the list of ports, the below code is going to scan. You can define other ports to, the ones that you want to scan.

exist=[] : It stores the open ports in this list.

def scan(portnum): functions that takes the port number to scan using socket connect.

sock.settimeout(1): sets the timeout for the socket, so the scan takes that as default time to connect.

exist.extend([i]):extend() is the function for list in python. It adds more list elements, hence extending the list. We are inserting the open ports in exist list.

The program to run takes exactly one argument which is the target address.

CODE:

#!/usr/bin/python3
import socket
import sys

portnum=[21,22,23,25,80,8080]
exist=[]

def scan(portnum):
	
	try:	
		target=sys.argv[1]
		ip=socket.gethostbyname(target)
		print(portnum)
		for i in portnum:

			try:	
				print("[?]Working on port "+str(i)+"...")
		                #socket object creation
				sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
				sock.settimeout(1)
				#try to connect to ip on the port i.
				r=sock.connect_ex((ip,i))
                 #if r that means the connection is successful then r will be 0 and hence the port num is inserted in exist list.			
				if(r == 0):
					exist.extend([i])
			except Exception as excp:
				print(excp)


			

	except Exception as e:
		print(e)
	finally:
		print("Open ports on "+target+" are: ")
		print(exist)
		
if __name__ == '__main__':
	if len(sys.argv) < 2:
		print("[-] Not Enough arguments.\n")
		usg()
	else:
		
		scan(portnum)

OUTPUT:

listscan using python hacking with python

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.