-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathport_scan.py
More file actions
67 lines (57 loc) · 2.36 KB
/
port_scan.py
File metadata and controls
67 lines (57 loc) · 2.36 KB
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
59
60
61
62
63
64
65
66
67
import socket # module for connections
import ipaddress # module for validating IP addresses
import time # module for timing functions (will be used for time duration of scan)
from colorama import init, Fore # module for colored text
init() #initialize colorama
GREEN = Fore.GREEN # Print in green if port is open
GRAY = Fore.LIGHTBLACK_EX # Print in gray if port is closed
RESET = Fore.RESET # Reset to default color
def is_port_open(host, port):
#Check if a specific port is open on a given host
#creates a new socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # socket.AF_INET & socket.SOCK_STREAM = Use IPv4 TCP socket
# if target slow or unresponsive, give up after 1 sec
s.settimeout(1)
try:
# tries to connect to the specified host using that port
s.connect((host, port))
except:
# cannot connect to the port; port is closed
return False
else:
# connection successful; port is open
return True
finally:
# closes socket after connection attempt
s.close()
# defined count for open ports
openPorts = 0
# get ip or hostname from user input
host = input("Enter the host IP address or domain name to scan: ")
num_ports = int(input("Enter how many ports to increment through (large number ==> scan takes more time..):"))
ip = socket.gethostbyname(host) # also accept IPs (user can also enter a valid IP; method will return it)
try:
# Validate the host input and check if it's a valid IP address
ipaddress.ip_address(ip)
except ValueError:
print(f"{GRAY}[-] Invalid IP address{RESET}")
exit()
# record start time
start_time = time.time()
# iterate through ports 1 to number of ports
for port in range(1, num_ports):
if is_port_open(host, port):
# Print open ports in green
print(f"{GREEN}[+] Port {port} is open! {RESET}")
openPorts = openPorts + 1
else:
# Print closed ports in gray and overwrite the line for better readability
print(f"{GRAY}[-] Port {port} is closed.. {RESET}", end='\r')
#record end time
end_time = time.time()
# calculate total runtime in seconds
duration = end_time - start_time
# prints message and count after scan
print(f"{GREEN}[+++] Completed port scan!", end="\n")
print(f"{GREEN}[+++] {openPorts} ports are open on {host}.")
print(f"{GREEN}[+++] Scan completed in {duration:.2f} seconds.")