-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnmapscanner.py
91 lines (77 loc) · 2.4 KB
/
nmapscanner.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
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env python3
"""Scanning ports
Initial command: pip install python-nmap
Usage: $ python3 nmapscanner.py <url>
"""
import json
import socket
import sys
import nmap
art = """
_ _______ _______ _______
( ( /|( )( ___ )( ____ )
| \ ( || () () || ( ) || ( )|
| \ | || || || || (___) || (____)|
| (\ \) || |(_)| || ___ || _____)
| | \ || | | || ( ) || (
| ) \ || ) ( || ) ( || )
|/ )_)|/ \||/ \||/
"""
def nmap_scanner(target: str) -> None:
"""Scans 21,22,80,139,443,8080 of the target
Args:
target (str): The target to be scanned
"""
# Ports to scan
ports = [21, 22, 80, 139, 443, 8080]
try:
# Loops over ports and gets information from resulting dictionary
scanner = nmap.PortScanner()
print(f"[!] Scanning {target} for default ports...\n")
for port in ports:
portscan = scanner.scan(target, str(port))
print(f"Port {port}:")
ip = next(iter(portscan["scan"].keys()))
state = portscan["scan"][ip]["tcp"][port]["state"]
name = portscan["scan"][ip]["tcp"][port]["name"]
if state == "open":
print(json.dumps(portscan["scan"][ip]["tcp"][port], indent=2))
else:
print(f" {state} - {name}")
except Exception as e:
print(f"Error: {e}")
print("NMAP scan failed, exiting...")
sys.exit(1)
def python_scanner(target: str) -> None:
"""Scans all the ports of a target
Args:
target (str): The target to be scanned
"""
open_ports = []
ports = range(1, 65535)
for port in ports:
sys.stdout.flush()
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.5)
r = sock.connect_ex((target, port))
if r == 0:
print(f"Port {port} (open) found")
open_ports.append(port)
sock.close()
except Exception as e:
pass
if open_ports:
print("Found open ports:")
print(sorted(open_ports))
else:
print("No open ports found.")
if __name__ == "__main__":
if len(sys.argv) < 2:
print(f"Usage: python3 {sys.argv[0]} <target>")
sys.exit(1)
print(art)
ip = sys.argv[1]
print(f"Scanning {ip}...")
# nmap_scanner(ip)
python_scanner(ip)