-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnmapy.py
More file actions
139 lines (105 loc) · 3.88 KB
/
nmapy.py
File metadata and controls
139 lines (105 loc) · 3.88 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import os
import time
import vulnerability_scan
from pathlib import Path
def vuln_scan_switch() -> bool:
"""
Toggle vulnerability scans on or off.
Returns:
bool: True if the input is 'y', False if it is 'N'.
Will retry the question for invalid input.
"""
while True:
user_input = (
input("Would you to scan for vulnerabilities? (y/n): ").strip().lower()
)
if user_input not in ["y", "n"]:
print("Invalid input. Please enter 'y' or 'n'.")
else:
break
# Assign based on user input
vuln_scan = True if user_input.lower() == "y" else False
if vuln_scan:
print("The computer will scan for vulnerabilities")
else:
print("The computer will not scan for vulnerabilities")
return vuln_scan
def validate_ip(ip: str) -> bool:
"""
Check if the input is a valid IPv4 adress.
Args:
ip (str): The string of the IP address to validate.
Returns:
bool: True if the IP address is valid, False otherwise.
"""
# Check if each part of the ip address is an integer in a valid range of 0 to 255.
try:
return all(0 <= int(part) < 256 for part in ip.split("."))
except ValueError:
return False
vuln_scan = vuln_scan_switch()
# Create config.txt if it does not exist.
# if not Path.cwd().rglob("config.txt"):
# Path("config.txt").touch()
# content = []
print("Scanning the network")
os.system("ip a")
while True:
ip = input("Enter the ip address of the network you would like to scan: ")
if not validate_ip(ip):
print("Invalid Ipv4 format. Try again.")
else:
break
# Construct base IP address by taking the first three octets from the user's input
base_ip = "{}.{}.{}".format(*ip.split(".")[:3])
file_name = time.strftime("%Y-%m-%d_%H-%M-%S") + "_hosts.txt"
# Iterate over last octet to scan the whole subnet
for i in range(256):
if i > 0:
ip_scan = "{}.{}".format(base_ip, i)
print("\nScanning " + ip_scan)
response = os.popen("sudo nmap -sS {}".format(ip_scan)).read()
if "Host seems down" in response:
print("{} is down\n".format(ip_scan))
else:
# host_info = os.popen("host {}".format(ip_scan)).read()
host_info = response.split("\n")
print(host_info)
host_line = host_info[1].split(" ")[4]
#host_line = host_info.split("\n")[0].split()[4] # Assuming the 5th word is the hostname
print("The host is: " + host_line)
# Append IP address and its status to content list
content = "{} | {}{}\n".format(ip_scan, host_line, " is up" if not "down" in response else "")
try:
with open("scan_history/" + file_name, "a") as file:
# for content in content:
file.write(content)
file.close()
except FileNotFoundError:
print("Error: File {} not found!")
exit(1)
time.sleep(1)
# Create scan_history directory if it does not exist.
scan_history_dir = Path("scan_history")
scan_history_dir.mkdir(parents=True, exist_ok=True)
file_path = scan_history_dir / file_name
file_path.touch()
files_in_dir = os.listdir()
if "config.txt" not in files_in_dir:
os.system("touch config.txt")
with open("config.txt", "r") as file:
content_config = file.read()
file.close()
if content_config.__contains__("newest scan = "):
with open("config.txt", "w") as file:
file.write("newest scan = scan_history/" + file_name)
file.close()
else:
with open("config.txt", "w") as file:
file.write("newest scan = scan_history/" + file_name)
file.close()
print("Networkmapping completed")
if vuln_scan:
print("\nStarting vulnerability scan")
vulnerability_scan.vulnerability_scan(file_name)
print("\nVulnerability scan completed")