-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPortScanner.py
58 lines (49 loc) · 1.73 KB
/
PortScanner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/python3
import socket
import pyfiglet
import os
# Prints logo
logo_text = pyfiglet.figlet_format("Port Scanner")
print(logo_text)
# Constants
ADDRESS_FAMILY = socket.AF_INET
SOCKET_TYPE = socket.SOCK_STREAM
# Creates socket object
s = socket.socket(ADDRESS_FAMILY, SOCKET_TYPE)
# Gets user input and removes any carriage return characters from the input, if the code is running on Windows OS
if os.name == 'nt':
host = input("Please enter the Target IP: ").replace('\r', '')
port_range = input("Please enter the port range: ").replace('\r', '')
else:
host = input("Please enter the Target IP: ")
port_range = input("Please enter the port range: ")
# Parses user input and validates them
try:
socket.inet_aton(host) # converts an IPv4 address string to its 32-bit binary format
except socket.error:
print("Invalid IP address")
exit()
try:
start_port, end_port = map(int, port_range.split('-'))
if start_port < 1 or end_port > 65535:
raise ValueError
except (ValueError, socket.error):
print("Invalid port range")
exit()
# Define port scanner function
def portScanner(host, port):
try:
result = s.connect_ex((host, port)) # s.connect_ex returns an error code if the connection attempt fails
if result == 0:
print(f"Port {port} is open")
else:
print(f"Port {port} is closed")
except socket.gaierror:
print("Hostname could not be resolved")
exit()
except socket.error:
print("Could not connect to server")
exit()
# Uses a for loop to iterate over the range of ports to scan and invokes the portScanner function to perform the scan
for port in range(start_port, end_port + 1):
portScanner(host, port)