r/ScriptSwap • • Dec 22 '12

[PYTHON] Basic Port Scanning Utility

import socket
import argparse
import csv

# Invoke argparse() as object 'parser' to catch commandline        arguments.  
parser = argparse.ArgumentParser(
	description='Scan for open ports on targethost.')
parser.add_argument(
	'ipaddress', help="Enter the IP address of the host you want to scan.")
parser.add_argument(
	'port', help="Enter the Port you would like to scan on the host.",
	type=int, nargs='?', default=0)
parser.add_argument(
	"-s", "--silent", help="silencec printed output", action="store_true")

# Define function for creating and opening socket connections to targets.  
def create_socket(address, port):	
s = socket.socket()
try:
	s.connect((address, port))
	return True
except:
	return False
	
# Define CSV writer function.
def writer(address, port, status):
with open('results.csv', 'ab') as f: # Append, must delete csv manually
	writer = csv.writer(f)
	writer.writerows([(address, port, status)])

# Define function for silent scanning of all ports  .
def scan_all_silent(address, port):
for x in range(1, 65536):
	s = create_socket(address, x)
	if s == True:
		write_csv = writer(address, x, 'open')
	if s == False:
		write_csv = writer(address, x, 'closed')

# Define function for scanning specific port silently.
def scan_spec_port_silent(address, port):
s = create_socket(address, port)
if s == True:
	write_csv = writer(address, port, 'open')
if s == False:
	write_csv = writer(address, port, 'closed')
	
# Define function for scanning all ports with print output.
def scan_all_with_print(address, port):
for x in range(1, 65536):
	s = create_socket(address, x)
	if s == True:
		print "IP: %s PORT: %d STATUS: Open" % (address, x)
	if s == False:
		print "IP: %s PORT: %d STATUS: Closed" % (address, x)

# Define function for scanning specific port with print output.
def scan_spec_port_with_print(address, port):
s = create_socket(address, port)
if s == True:
	print "IP: %s PORT: %d STATUS: Open" % (address, port)
if s == False:
	print "IP: %s PORT: %d STATUS: Closed" % (address, port)

# Main program logic and command line argument parsing.
args = parser.parse_args()
address = args.ipaddress
port = args.port
silence = args.silent

if silence == True:
if port == 0:
	scan = scan_all_silent(address, port)
else:
	scan = scan_spec_port_silent(address, port)
else:
if port == 0:
	scan = scan_all_with_print(address, port)
else:
	scan = scan_spec_port_with_print(address, port)
3 Upvotes

0 comments sorted by