TCP Full Connect Scan with Python

A simple tcp full connect port scanner in Python:

import optparse
from socket import *
 
def connect(targetHost, targetPort):
	try:
		connsocket = socket(AF_INET, SOCK_STREAM)
		connsocket.connect((targetHost, targetPort))
		connsocket.close()
		print '%d/tcp port openn'%targetPort
	except:
		print '%d/tcp port closedn'%targetPort
 
def scanner(targetHost, targetPorts):
	try:
		ip = gethostbyname(targetHost)
	except:
		print "unable to resolve '%s': Unknown hostn"%targetHost
		return
 
	try:
		targetName = gethostbyaddr(ip)
		print 'nScanning target ' + targetName[0] + 'n'
	except:
		print 'nScanning target ' + ip + 'n'
	setdefaulttimeout(1)
 
	for targetPort in targetPorts:
		print 'Scanning port ' + targetPort
		connect(targetHost, int(targetPort))
 
def main():
	options = {}
	parser = optparse.OptionParser('usage: %prog -H <target host> -p <target port>')
	parser.add_option('-H', '--host', dest='target_host', type='string', help='specify target host')
	parser.add_option('-p', '--ports', dest='target_port', type='string', help='specify target port[s] separated by comma')
 
	(options, args) = parser.parse_args()
	target_host = options.target_host
	target_ports = str(options.target_port).split(',')
 
	if(target_host == None) | (target_ports[0] == None):
		print parser.usage
		exit(0)
 
	scanner(target_host, target_ports)
 
if __name__ == '__main__':
    main()
Categories: Python Tags: , , ,
%d bloggers like this: