Port scanner with sockets

Sockets are the fundamental building block for network communications and in an easy way we can check whether a specific port is open, closed, or filtered by calling the connect_ex method.

For example, we could have a function that accepts by parameters an IP and a list of ports and return for each port whether it is open or closed.

In this example, we need to import the socket and sys modules. If we execute the function from our main program, we see how it checks each of the ports and returns whether it is open or closed for a specific IP address. The first parameter can be either an IP address or a domain name since the module is able to resolve a name from an IP and vice versa.

You can find the following code in the check_ports_socket.py file inside the port_scan folder:

import socket
import sys

def checkPortsSocket(ip,portlist):
try:
for port in portlist:
sock= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.settimeout(5)
result = sock.connect_ex((ip,port))
if result == 0:
print ("Port {}: Open".format(port))
else:
print ("Port {}: Closed".format(port))
sock.close()
except socket.error as error:
print (str(error))
print ("Connection error")
sys.exit()

checkPortsSocket('localhost',[80,8080,443])

The following Python code will allow you to scan a local or remote host for open ports. The program scans for select ports on a certain IP address entered by the user and reflects the open ports back to the user. If the port is closed, it also shows information about the reason for that, for example by timeout connection.

You can find the following code in the socket_port_scanner.py file inside the port_scan folder.

The script starts with information related to the IP address and ports introduced by the user:

#!/usr/bin/env python
#--*--coding:UTF-8--*--
# Import modules
import socket
import sys
from datetime import datetime
import errno

# RAW_INPUT IP / HOST
remoteServer = raw_input("Enter a remote host to scan: ")
remoteServerIP = socket.gethostbyname(remoteServer)

# RAW_INPUT START PORT / END PORT
print "Please enter the range of ports you would like to scan on the machine"
startPort = raw_input("Enter a start port: ")
endPort = raw_input("Enter a end port: ")

print "Please wait, scanning remote host", remoteServerIP
#get Current Time as T1
t1 = datetime.now()

We continue the script with a for loop from startPort to endPort to analyze each port in between.We finish by showing the total time to complete the port scanning:

#Specify Range - From startPort to startPort
try:
for port in range(int(startPort),int(endPort)):
print ("Checking port {} ...".format(port))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((remoteServerIP, port))
if result == 0:
print "Port {}: Open".format(port)
else:
print "Port {}: Closed".format(port)
print "Reason:",errno.errorcode[result]
sock.close()
# If interrupted
except KeyboardInterrupt:
print "You pressed Ctrl+C"
sys.exit()
# If Host is wrong
except socket.gaierror:
print 'Hostname could not be resolved. Exiting'
sys.exit()
# If server is down
except socket.error:
print "Couldn't connect to server"
sys.exit()
#get current Time as t2
t2 = datetime.now()
#total Time required to Scan
total = t2 - t1
# Time for port scanning
print 'Port Scanning Completed in: ', total

In the execution of the previous script, we can see ports that are open and the time in seconds for complete port-scanning:

The following Python script will allow us to scan an IP address with the portScanning and socketScan functions. The program scans for selected ports on a specific domain resolved from the IP address entered by the user by parameter.

In this script, the user must enter as mandatory parameters the host and a port, separated by a comma:

You can find the following code in the socket_portScan.py file inside the port_scan folder:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import optparse
from socket import *
from threading import *

def socketScan(host, port):
try:
socket_connect = socket(AF_INET, SOCK_STREAM)
socket_connect.connect((host, port))
results = socket_connect.recv(100)
print '[+] %d/tcp open ' % port
print '[+] ' + str(results)
except:
print '[-] %d/tcp closed ' % port
finally:
socket_connect.close()

def portScanning(host, ports):
try:
ip = gethostbyname(host)
except:
print "[-] Cannot resolve '%s': Unknown host" %host
return
try:
name = gethostbyaddr(ip)
print ' [+] Scan Results for: ' + name[0]
except:
print ' [+] Scan Results for: ' + ip

for port in ports:
t = Thread(target=socketScan,args=(host,int(port)))
t.start()

This is our main program when we get mandatory parameters host and ports for the script execution. Once we have obtained these parameters, we call the portScanning function which will resolve the IP address and host name, and will call the socketScan function that will use the socket module to determine the port state:

def main():
parser = optparse.OptionParser('socket_portScan '+ '-H <Host> -P <Port>')
parser.add_option('-H', dest='host', type='string', help='specify host') parser.add_option('-P', dest='port', type='string', help='specify port[s] separated by comma')

(options, args) = parser.parse_args()
host = options.host
ports = str(options.port).split(',')

if (host == None) | (ports[0] == None):
print parser.usage
exit(0)

portScanning(host, ports)

if __name__ == '__main__':
main()
python .socket_portScan.py -H 8.8.8.8 -P 80,21,22,23

In the execution of the previous script, we can see that all ports are closed in the google-public-dns-a.google.com domain:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.188.138