-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathPortScanner.py
58 lines (45 loc) · 1.41 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
import socket
import sys
def connect_to_ip(ip, port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip, port))
return sock
except Exception:
return None
def scan_port(ip, port, timeout):
socket.setdefaulttimeout(timeout)
sock = connect_to_ip(ip, port)
if sock:
print('Able to connect to: {0}:{1}').format(ip, port)
sock.close()
else:
print('Not able to connect to: {0}:{1}').format(ip, port)
# Get the IP / domain from the user
ip_domain = raw_input("Enter the ip or domain: ")
if ip_domain == '':
print('You must specify a host!')
sys.exit(0)
# Get the port range from the user
port = raw_input("Enter the port range (Ex 20-80): ")
if port == '':
print('You must specify a port range!')
sys.exit(0)
# Optional: Get the timeout from the user
timeout = raw_input("Timeout (Default=5): ")
if not timeout:
timeout = 5
port_range = port.split("-")
# Get the IP address if the host name is a domain
try:
ip = socket.gethostbyname(ip_domain)
except Exception:
print('There was an error resolving the domain')
sys.exit(1)
# If the user only entered one port we will only scan the one port
# otherwise scan the range
if len(port_range) < 2:
scan_port(ip, int(port), int(timeout))
else:
for port in range(int(port_range[0]), int(port_range[1])+1):
scan_port(ip, int(port), int(timeout))