Port Scanning with sockets in python

Port Scanning with sockets in python

A port scanner is a tool or software application designed to identify open ports and services on a computer network, thus facilitating the detection of potential vulnerabilities. It works by sending network requests to a range of ports on a target system and analyzing the responses.

Key Concepts:

  1. Port:
    • In networking, a port is a communication endpoint. Ports are identified by a numeric value, and each port is associated with a specific protocol or service.
  2. Open Port:
    • An open port is a port on a system that is actively accepting incoming network connections. It indicates that there is a service or application running on that port.
  3. Closed Port:
    • A closed port is a port that is not actively accepting incoming connections. It means there is no service running on that port.
  4. Port Scanning:
    • Port scanning involves systematically probing a target system for open ports. It is a reconnaissance technique used by network administrators to identify the services running on a system.
  5. Types of Scans:
    • TCP Connect Scan: Connects to each port and determines whether it is open or closed by establishing a full TCP connection.
    • SYN Scan (Half-Open Scan): Sends SYN packets to initiate a TCP connection but does not complete the connection. It analyzes the response to determine open/closed ports.
    • UDP Scan: Checks for open UDP ports by sending UDP packets and analyzing the responses.
    • XMAS Scan: Sends packets with the FIN, URG, and PUSH flags set to identify open ports.
    • NULL Scan: Sends packets with no TCP flags set to identify open ports.
  6. Use Cases:
    • Security Audits: Security professionals use port scanners to identify potential vulnerabilities in a network.
    • Network Discovery: Administrators use port scanning to discover active hosts and services on a network.
    • Troubleshooting: Identifying open or closed ports can help diagnose network connectivity issues.
  7. Ethical Considerations:
    • Port scanning should be conducted ethically and in compliance with legal standards. Unauthorized scanning of systems without permission is considered illegal and unethical.

Basic Port Scanner

  1. Shebang Line:
Python
   #!/usr/bin/python
  • The shebang line specifies that the script should be executed using the Python interpreter.
  1. Importing socket and sys Modules:
Python
   import socket
   import sys
  • The script imports the socket module for socket-related operations and the sys module for system-specific functionality.
  1. Defining the checkPortsSocket Function:
Python
   def checkPortsSocket(ip, portlist):
  • A function named checkPortsSocket is defined, which takes an IP address (ip) and a list of ports (portlist) as parameters.
  1. Iterating Through Port List and Checking Ports:
Python
   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 {}: \t Open".format(port))
           else:
               print("Port {}: \t Closed".format(port))
           sock.close()
  • The function uses a try block to catch potential exceptions during socket operations.
  • It iterates through each port in the specified portlist.
  • For each port, it creates a socket (sock) and sets a timeout of 5 seconds.
  • It uses sock.connect_ex((ip, port)) to check the connection status. If the result is 0, the port is considered open; otherwise, it is closed.
  • The function prints the port status (open or closed) for each port.
  1. Handling Socket Errors:
Python
   except socket.error as error:
       print(str(error))
       print("Connection error")
       sys.exit()
  • If a socket.error occurs, it prints the error message, prints a connection error message, and exits the script.
  1. Invoking the Function:
Python
   checkPortsSocket('localhost', [21, 22, 80, 8080, 443])
  • The script invokes the checkPortsSocket function with the IP address 'localhost' and a list of ports [21, 22, 80, 8080, 443].
Python
#!/usr/bin/python

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 {}: \t Open".format(port))
            else:
                print ("Port {}: \t Closed".format(port))
            sock.close()
    except socket.error as error:
        print (str(error))
        print ("Connection error")
        sys.exit()

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

This script defines a function to check the status of multiple ports on a specified IP address. It uses socket operations, sets a timeout for each connection attempt, and prints whether each port is open or closed. The function is invoked with a sample IP address and port list.

Socket Port Scanner

Python script is designed to perform a simple port scanning on a remote host. Port scanning is a technique used to discover open ports on a target system, providing information about the services running on those ports.

Import Statements

Python
import socket
import sys
from datetime import datetime
import errno

These statements import necessary modules for socket operations, system-related functionality, and datetime for measuring the time taken by the scan.

User Input

Python
remoteServer = input("Enter a remote host to scan: ")
remoteServerIP = socket.gethostbyname(remoteServer)

The user is prompted to enter the hostname of the remote server they want to scan. The script then resolves this hostname to an IP address using socket.gethostbyname().

Port Range Input

Python
startPort = input("Enter a start port: ")
endPort = input("Enter an end port: ")

The user is prompted to specify a range of ports to scan. The start and end port values are taken as input.

Port Scanning Process

Python
time_init = datetime.now()

try:
    for port in range(int(startPort), int(endPort)):
        # ...
except KeyboardInterrupt:
    # ...
except socket.gaierror:
    # ...
except socket.error:
    # ...

The script enters a try block where it iterates through the specified range of ports using a for loop. Inside the loop, a socket is created, and socket.connect_ex() is used to check if the connection to the specified port is successful (result == 0) or not. The script then prints whether the port is open or closed along with a reason in case of closure.

Exception Handling

The script includes exception handling for potential errors:

  • KeyboardInterrupt: If the user interrupts the scanning process with Ctrl+C.
  • socket.gaierror: Handles errors related to hostname resolution.
  • socket.error: Catches general socket errors.

Time Measurement

Python
time_finish = datetime.now()
total = time_finish - time_init
print('Port Scanning Completed in: ', total)

The script measures the total time taken for the port scanning process and prints the result.

Python
#!/usr/bin/env python

import socket
import sys
from datetime import datetime
import errno

remoteServer    = input("Enter a remote host to scan: ")
remoteServerIP  = socket.gethostbyname(remoteServer)

print("Please enter the range of ports you would like to scan on the machine")
startPort    = input("Enter a start port: ")
endPort    = input("Enter a end port: ")

print("Please wait, scanning remote host", remoteServerIP)

time_init = datetime.now()

try:
	for port in range(int(startPort),int(endPort)):
		print ("Checking port {} ...".format(port))
		sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		sock.settimeout(5)
		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()

except KeyboardInterrupt:
	print("You pressed Ctrl+C")
	sys.exit()
except socket.gaierror:
	print('Hostname could not be resolved. Exiting')
	sys.exit()
except socket.error:
	print("Couldn't connect to server")
	sys.exit()

time_finish = datetime.now()
total =  time_finish - time_init
print('Port Scanning Completed in: ', total)

The script takes user input for the remote host and port range, then attempts to connect to each port in the specified range on the remote host. It reports whether each port is open or closed, along with a reason for closure. The total time taken for the scan is then displayed.

Advance Port Scanner

Import Statements

Python
#!/usr/bin/python

import optparse
from socket import *
from threading import *
  1. Shebang Line: Specifies the interpreter to be used for running the script.
  2. Import Statements:
  • optparse: Used for parsing command-line options and arguments.
  • socket: Provides low-level networking functionality.
  • Thread from threading: Enables the use of threads for concurrent execution.

Socket Scan Function

Python
def socketScan(host, port):
    try:
        socket_connect = socket(AF_INET, SOCK_STREAM)
        socket_connect.settimeout(5)
        result = socket_connect.connect((host, port))
        print('[+] %d/tcp open' % port)
    except Exception as exception:
        print('[-] %d/tcp closed' % port)
        print('[-] Reason:%s' % str(exception))
    finally:
        socket_connect.close()
  1. Function Definition: socketScan function is defined to check whether a given port is open on the specified host.
  2. Socket Creation: Creates a socket using socket(AF_INET, SOCK_STREAM).
  3. Connection Attempt: Attempts to connect to the specified host and port.
  4. Prints Result: Prints whether the port is open or closed and, in case of closure, prints the reason.

Port Scanning Function

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

    for port in ports:
        t = Thread(target=socketScan, args=(ip, int(port)))
        t.start()
  1. Function Definition: portScanning function is defined to initiate the port scanning process.
  2. Host Resolution: Resolves the host to its IP address using gethostbyname.
  3. Prints Scan Information: Prints the scan results, including the target IP address.
  4. Threaded Port Scanning: Iterates through the specified ports and creates a new thread for each port using Thread. Each thread runs the socketScan function.

Main Function

Python
def main():
    parser = optparse.OptionParser('socket_portScan ' + '-H  -P ')
    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()
  1. Main Function Definition: main function is defined to handle command-line options and initiate the port scanning process.
  2. Option Parsing: Uses optparse.OptionParser to parse command-line options for host and port.
  3. Command-line Argument Extraction: Extracts the host and port values from the command line.
  4. Input Validation: Checks if both host and at least one port are provided; if not, prints usage information and exits.
  5. Port Scanning Initiation: Calls the portScanning function with the provided host and port values.

Execution Trigger

Python
if __name__ == '__main__':
    main()

Ensures that the main function is called when the script is executed directly.

Python
#!/usr/bin/python

import optparse
from socket import *
from threading import *

def socketScan(host, port):
	try:
		socket_connect = socket(AF_INET, SOCK_STREAM)
		socket_connect.settimeout(5)
		result = socket_connect.connect((host, port))
		print('[+] %d/tcp open' % port)
	except Exception as exception:
		print('[-] %d/tcp closed' % port)
		print('[-] Reason:%s' % str(exception))
	finally:
		socket_connect.close()	

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

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

def main():
	parser = optparse.OptionParser('socket_portScan '+ '-H  -P ')
	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()

To Run This Code

Bash
$ python3 socket_advanced_port_scan.py -H www.awjunaid.com -P 80,81,82,31

This script is a basic command-line tool for multi-threaded port scanning. It takes a target host and a list of ports as input, resolves the host, and then concurrently checks the status of each port using threads. The results are printed on the console.

Total
3
Shares

Leave a Reply

Previous Post
Resolving IPS domains, addresses, managing exception and reverse lookup command

Resolving IPS domains, addresses, managing exception and reverse lookup command

Next Post
Implementing the TCP server and Client in Python

Implementing the TCP server and Client in Python

Related Posts