Creating a Python Script to Scan for Open Ports and Services on a Network

Network security is a crucial aspect of maintaining safe and reliable computer systems. One common task for network administrators is identifying open ports and the services running on them. Creating a Python script to scan for open ports can help detect vulnerabilities and ensure that only necessary services are accessible.

Understanding Network Ports and Services

Network ports are endpoints for communication between devices. Each port is associated with a specific service or application. Common ports include 80 for HTTP, 443 for HTTPS, and 22 for SSH. Knowing which ports are open helps in assessing network security and preventing unauthorized access.

Creating a Python Port Scanner

Python provides several libraries that facilitate network scanning, such as socket. Using this library, you can write a script to check whether specific ports are open on a target IP address or range.

Basic Port Scanner Script

Below is a simple example of a Python script that scans a range of ports on a target IP address:

Note: Always obtain permission before scanning networks that you do not own.

“`python
import socket

target_ip = ‘192.168.1.1’
start_port = 1
end_port = 1024

for port in range(start_port, end_port + 1):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.5)
result = sock.connect_ex((target_ip, port))
if result == 0:
print(f’Port {port} is open’)
sock.close()
“`

Enhancing the Script to Detect Services

To identify services running on open ports, you can attempt to connect to common service ports and analyze the response. For example, connecting to port 80 may return an HTTP header, indicating a web server.

Service Detection Example

Here’s an example of a simple service detection method:

Note: More sophisticated detection may require specific protocols and libraries.

“`python
import socket

def check_service(ip, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
try:
result = sock.connect_ex((ip, port))
if result == 0:
sock.send(b’HEAD / HTTP/1.1\r\nHost: ‘ + bytes(ip, ‘utf-8′) + b’\r\n\r\n’)
response = sock.recv(1024).decode(‘utf-8’)
print(f’Port {port} is open. Service response:’)
print(response.split(‘\\r\\n’)[0])
else:
print(f’Port {port} is closed’)
except Exception as e:
print(f’Error connecting to port {port}: {e}’)
finally:
sock.close()

target_ip = ‘192.168.1.1’
common_ports = [80, 22, 443, 21, 25]
for port in common_ports:
check_service(target_ip, port)
“`

Conclusion

Creating a Python script for port scanning is a powerful way to assess network security. By customizing the script, you can detect open ports and identify the services running on them. Remember to always perform scans ethically and with proper authorization to avoid legal issues.