-
Notifications
You must be signed in to change notification settings - Fork 0
/
port_scanner.py
78 lines (73 loc) · 2.36 KB
/
port_scanner.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import socket
import sys
from datetime import datetime
#handle arguments to define target
if len(sys.argv) <= 2:
print("You need to specify a single port (e.g. 80), multiple ports (e.g. 21, 22, 80) , or a port range (e.g. 1-65535).")
aux = input("Range: ")
if aux.isdigit() == False and (aux.find("-") == -1 and aux.find(",") == -1):
print("You need to specify a single port (e.g. 80), multiple ports (e.g. 21, 22, 80) , or a port range (e.g. 1-65535).")
sys.exit(0)
else:
port = aux
if len(sys.argv) == 1:
host = input("You need to specify an IP address or hostname: ")
host = socket.gethostbyname(host)
else:
host = socket.gethostbyname(sys.argv[1])
else:
if sys.argv[2].isdigit() == False:
if sys.argv[2].find("-") != 1 or sys.argv[2].find(",") != 1:
host = socket.gethostbyname(sys.argv[1])
port = sys.argv[2]
else:
sys.exit(0)
else:
host = socket.gethostbyname(sys.argv[1])
port = sys.argv[2]
#add banner
print("-" * 50)
print("Scanning target: " + host)
print("Time initiated: " + str(datetime.now()))
#handling scan
try:
if port.isdigit():
#single port scan
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.5)
res = sock.connect_ex((host,int(port)))
if res == 0:
print("Open port: ", port)
sock.close()
elif port.find("-") != -1:
#port range scan
aux = port.split('-')
for p in range(int(aux[0]),int(aux[1])):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.1) #100 milisenconds
res = sock.connect_ex((host, p))
if res == 0:
print("Open port: ", p)
sock.close()
else:
#port list scan
aux = port.split(',')
for p in aux:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.3) #300 milisenconds
res = sock.connect_ex((host, int(p.strip())))
if res == 0:
print("Open port: ", p)
sock.close()
except KeyboardInterrupt:
print("\n\nScan interrupted by keyboard.")
sys.exit(0)
except socket.gaierror:
print("\nHostname could not be resolved.")
sys.exit(1)
except socket.error:
print("\nCouldn't connect to target.")
sys.exit(1)
except:
print("\nUnknown exception.")
sys.exit(1)