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:
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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
- Shebang Line:
#!/usr/bin/python- The shebang line specifies that the script should be executed using the Python interpreter.
- Importing
socketandsysModules:
import socket
import sys- The script imports the
socketmodule for socket-related operations and thesysmodule for system-specific functionality.
- Defining the
checkPortsSocketFunction:
def checkPortsSocket(ip, portlist):- A function named
checkPortsSocketis defined, which takes an IP address (ip) and a list of ports (portlist) as parameters.
- Iterating Through Port List and Checking Ports:
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
tryblock 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.
- Handling Socket Errors:
except socket.error as error:
print(str(error))
print("Connection error")
sys.exit()- If a
socket.erroroccurs, it prints the error message, prints a connection error message, and exits the script.
- Invoking the Function:
checkPortsSocket('localhost', [21, 22, 80, 8080, 443])- The script invokes the
checkPortsSocketfunction with the IP address'localhost'and a list of ports[21, 22, 80, 8080, 443].
#!/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
import socket
import sys
from datetime import datetime
import errnoThese statements import necessary modules for socket operations, system-related functionality, and datetime for measuring the time taken by the scan.
User Input
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
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
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
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.
#!/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
#!/usr/bin/python
import optparse
from socket import *
from threading import *- Shebang Line: Specifies the interpreter to be used for running the script.
- Import Statements:
optparse: Used for parsing command-line options and arguments.socket: Provides low-level networking functionality.Threadfromthreading: Enables the use of threads for concurrent execution.
Socket Scan Function
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()- Function Definition:
socketScanfunction is defined to check whether a given port is open on the specified host. - Socket Creation: Creates a socket using
socket(AF_INET, SOCK_STREAM). - Connection Attempt: Attempts to connect to the specified host and port.
- Prints Result: Prints whether the port is open or closed and, in case of closure, prints the reason.
Port Scanning Function
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()- Function Definition:
portScanningfunction is defined to initiate the port scanning process. - Host Resolution: Resolves the host to its IP address using
gethostbyname. - Prints Scan Information: Prints the scan results, including the target IP address.
- Threaded Port Scanning: Iterates through the specified ports and creates a new thread for each port using
Thread. Each thread runs thesocketScanfunction.
Main Function
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()- Main Function Definition:
mainfunction is defined to handle command-line options and initiate the port scanning process. - Option Parsing: Uses
optparse.OptionParserto parse command-line options for host and port. - Command-line Argument Extraction: Extracts the host and port values from the command line.
- Input Validation: Checks if both host and at least one port are provided; if not, prints usage information and exits.
- Port Scanning Initiation: Calls the
portScanningfunction with the provided host and port values.
Execution Trigger
if __name__ == '__main__':
main()Ensures that the main function is called when the script is executed directly.
#!/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
$ python3 socket_advanced_port_scan.py -H www.awjunaid.com -P 80,81,82,31This 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.