3
3
import sys
4
4
import ipaddress
5
5
6
+ # Check if the user has provided commandline arguments.
6
7
if len (sys .argv ) < 2 :
7
8
print ("Not enough commandline arguments." )
8
9
sys .exit ()
9
10
11
+ # Check if the IP address or website is valid or not.
10
12
try :
11
13
ipaddress .ip_address (sys .argv [1 ])
12
14
except ValueError :
20
22
else :
21
23
target_IP = sys .argv [1 ]
22
24
25
+ # create a list to store custom ports.
23
26
custom_ports = []
24
27
if len (sys .argv ) > 2 :
25
28
custom_ports = sys .argv [2 :]
26
29
30
+ # Method to scan a single port
27
31
def scan_port (target_IP , port ):
32
+ # Create a socket object.
28
33
s = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
34
+
35
+ # Set default timeout to 1 second.
29
36
socket .setdefaulttimeout (1 )
30
37
38
+ # Try to connect the target
31
39
result = s .connect_ex ((target_IP , port ))
32
40
41
+ # Check if connection was successful
33
42
if result == 0 :
34
43
print (f"Port { port } : \033 [92mOPEN\033 [0m" )
35
44
return port
36
45
37
46
print (f"Port { port } : \033 [91mCLOSED\033 [0m" )
38
47
return None
39
48
49
+ # List to hold open ports.
40
50
open_ports = []
41
51
52
+ # Create a context manager to spawn individual threads for each port.
42
53
with concurrent .futures .ThreadPoolExecutor () as executor :
43
54
55
+ # Check if the users has provided custom ports or not.
44
56
if len (custom_ports ) == 0 :
45
57
future_to_port = {
46
58
executor .submit (scan_port , target_IP , port ): port for port in range (65535 )
@@ -50,14 +62,20 @@ def scan_port(target_IP, port):
50
62
executor .submit (scan_port , target_IP , int (port )): port for port in custom_ports
51
63
}
52
64
65
+ # Run a loop to collect open ports.
53
66
for future in concurrent .futures .as_completed (future_to_port ):
67
+ # Get the selected port
54
68
port = future_to_port [future ]
55
69
try :
70
+ # Check if it a valid port.
56
71
open_port = future .result ()
57
72
except Exception as e :
73
+ # Print any errors.
58
74
print (f"Exception:{ e } " )
59
75
else :
76
+ # Add to the list if it's a valid port.
60
77
if open_port is not None :
61
78
open_ports .append (open_port )
62
79
80
+ # Finally print all the open ports.
63
81
print (f"Open Ports:{ open_ports } " )
0 commit comments