-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetwork_Device_And_Vulnerability_Scan.py
More file actions
474 lines (409 loc) · 16.3 KB
/
Network_Device_And_Vulnerability_Scan.py
File metadata and controls
474 lines (409 loc) · 16.3 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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
import os
import nmap
import psutil
import socket
import threading
import ipaddress
import json
from datetime import datetime
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QComboBox, QPushButton, QLabel, QListWidget, QSplitter,
QTreeWidget, QTreeWidgetItem, QMessageBox, QScrollArea, QSizePolicy)
from PyQt6.QtCore import Qt, QThread, pyqtSignal
def get_network_interfaces():
interfaces = []
for interface, addrs in psutil.net_if_addrs().items():
ip = None
subnet_mask = None
for addr in addrs:
if addr.family == socket.AF_INET:
ip = addr.address
subnet_mask = addr.netmask
break
if ip and subnet_mask:
interfaces.append({
'name': interface,
'ip': ip,
'subnet_mask': subnet_mask
})
return interfaces
def scan_network(network):
try:
nm = nmap.PortScanner()
scan_args = '-sn -v --max-retries 2 --host-timeout 30s'
nm.scan(hosts=network, arguments=scan_args)
online_hosts = []
for host in nm.all_hosts():
try:
host_status = nm[host].state()
if host_status == 'up':
hostname = nm[host].hostname() if nm[host].hostname() else ''
host_info = host
if hostname:
host_info = f"{host} ({hostname})"
online_hosts.append(host_info)
except KeyError:
continue
return online_hosts
except Exception as e:
print(f"Error during network scan: {str(e)}")
return []
def get_device_details(ip):
nm = nmap.PortScanner()
try:
nm.scan(ip, arguments='-sV -O')
details = {
'Operating System': '',
'Services': []
}
if ip in nm.all_hosts():
if 'osmatch' in nm[ip]:
os_matches = nm[ip]['osmatch']
if os_matches:
details['Operating System'] = os_matches[0]['name']
for proto in nm[ip].all_protocols():
ports = nm[ip][proto].keys()
for port in ports:
service = nm[ip][proto][port]
details['Services'].append({
'Port': port,
'Service': service.get('name', ''),
'Version': service.get('version', '')
})
return details
except Exception as e:
print(f"Error getting device details: {e}")
return {'Operating System': '', 'Services': []}
class ScanWorker(QThread):
finished = pyqtSignal(list)
def __init__(self, network):
super().__init__()
self.network = network
def run(self):
results = scan_network(self.network)
self.finished.emit(results)
class VulnScanWorker(QThread):
finished = pyqtSignal(dict)
def __init__(self, ip):
super().__init__()
self.ip = ip
def run(self):
results = get_device_details(self.ip)
self.finished.emit(results)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Network Scanner & Vulnerability Scanner")
self.setMinimumSize(800, 600)
# Initialize JSON file path
self.json_file_path = os.path.join("data_temp", "network_device_and_vulnerability_scan.json")
os.makedirs(os.path.dirname(self.json_file_path), exist_ok=True)
# Load existing data if available
self.scan_history = self.load_scan_history()
# Create main widget and layout
main_widget = QWidget()
self.setCentralWidget(main_widget)
main_layout = QVBoxLayout(main_widget)
# Create horizontal splitter
splitter = QSplitter(Qt.Orientation.Horizontal)
splitter.setHandleWidth(2)
# Left panel
left_panel = QWidget()
left_layout = QVBoxLayout(left_panel)
left_layout.setContentsMargins(5, 5, 5, 5)
# Interface selection
interface_group = QWidget()
interface_layout = QVBoxLayout(interface_group)
self.interface_label = QLabel("Select Network Interface:")
self.interface_label.setStyleSheet("font-size: 12pt; font-weight: bold; color: white;")
interface_layout.addWidget(self.interface_label)
self.interface_combo = QComboBox()
self.interface_combo.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.interface_combo.setStyleSheet("""
QComboBox {
padding: 5px;
border: 2px solid #3498db; /* Changed border color to blue */
border-radius: 5px;
background: #2c3e50; /* Dark background */
color: white; /* Text color */
min-height: 25px;
}
QComboBox::drop-down {
border: none;
width: 30px;
}
QComboBox::down-arrow {
image: none;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 7px solid #3498db; /* Blue triangle arrow */
margin-right: 8px;
}
QComboBox:hover {
border: 2px solid #2980b9; /* Darker blue on hover */
}
QComboBox QAbstractItemView {
background: #2c3e50; /* Dropdown menu background */
color: white; /* Dropdown menu text color */
selection-background-color: #3498db; /* Selected item background */
selection-color: white; /* Selected item text color */
border: 1px solid #3498db;
}
""")
interface_layout.addWidget(self.interface_combo)
# Manual IP range scan group
manual_scan_group = QWidget()
manual_scan_layout = QVBoxLayout(manual_scan_group)
manual_scan_label = QLabel("Manual IP Range Scan:")
manual_scan_label.setStyleSheet("font-size: 12pt; font-weight: bold; color: white;")
manual_scan_layout.addWidget(manual_scan_label)
self.ip_range_input = QComboBox()
self.ip_range_input.setEditable(True)
self.ip_range_input.setPlaceholderText("Enter IP range (e.g. 192.168.1.0/24)")
self.ip_range_input.setStyleSheet("""
QComboBox {
padding: 5px;
border: 2px solid #3498db;
border-radius: 5px;
background: #2c3e50;
color: white;
min-height: 25px;
}
QComboBox:editable {
background: #2c3e50;
}
QComboBox:hover {
border: 2px solid #2980b9;
}
""")
manual_scan_layout.addWidget(self.ip_range_input)
# Add after creating ip_range_input in __init__
common_ranges = [
"192.168.1.0/24",
"192.168.0.0/24",
"10.0.0.0/24",
"172.16.0.0/24"
]
self.ip_range_input.addItems(common_ranges)
self.manual_scan_button = QPushButton("Scan IP Range")
self.manual_scan_button.setStyleSheet("""
QPushButton {
background-color: #2ecc71;
color: white;
padding: 8px;
border-radius: 5px;
font-weight: bold;
}
QPushButton:hover {
background-color: #27ae60;
}
""")
manual_scan_layout.addWidget(self.manual_scan_button)
# Add the manual scan group to left_layout after interface_group
left_layout.addWidget(manual_scan_group)
# Scan button
self.scan_button = QPushButton("Scan Network")
self.scan_button.setStyleSheet("""
QPushButton {
background-color: #3498db;
color: white;
padding: 8px;
border-radius: 5px;
font-weight: bold;
}
QPushButton:hover {
background-color: #2980b9;
}
""")
interface_layout.addWidget(self.scan_button)
left_layout.addWidget(interface_group)
# Online devices list
self.online_label = QLabel("Online Devices:")
self.online_label.setStyleSheet("font-size: 12pt; font-weight: bold; color: white;")
left_layout.addWidget(self.online_label)
self.ip_list = QListWidget()
self.ip_list.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
self.ip_list.setStyleSheet("""
QListWidget {
border: 2px solid #bdc3c7;
border-radius: 5px;
padding: 5px;
}
QListWidget::item:selected {
background: #3498db;
color: white;
}
""")
left_layout.addWidget(self.ip_list)
# Vulnerability scan button
self.vuln_scan_button = QPushButton("Scan Vulnerabilities")
self.vuln_scan_button.setStyleSheet("""
QPushButton {
background-color: #e74c3c;
color: white;
padding: 8px;
border-radius: 5px;
font-weight: bold;
}
QPushButton:hover {
background-color: #c0392b;
}
""")
left_layout.addWidget(self.vuln_scan_button)
# Right panel
right_panel = QWidget()
right_layout = QVBoxLayout(right_panel)
right_layout.setContentsMargins(5, 5, 5, 5)
results_label = QLabel("Scan Results:")
results_label.setStyleSheet("font-size: 12pt; font-weight: bold; color: white;")
right_layout.addWidget(results_label)
self.result_tree = QTreeWidget()
self.result_tree.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
self.result_tree.setStyleSheet("""
QTreeWidget {
border: 2px solid #bdc3c7;
border-radius: 5px;
padding: 5px;
}
QTreeWidget::item:selected {
background: #3498db;
color: white;
}
QTreeWidget::item {
padding: 2px;
}
""")
self.result_tree.setHeaderLabels(["Detail", "Service", "Version"])
self.result_tree.setColumnWidth(0, 200)
self.result_tree.setColumnWidth(1, 200)
self.result_tree.setColumnWidth(2, 200)
right_layout.addWidget(self.result_tree)
# Add panels to splitter
splitter.addWidget(left_panel)
splitter.addWidget(right_panel)
splitter.setStretchFactor(0, 1)
splitter.setStretchFactor(1, 2)
# Add splitter to main layout
main_layout.addWidget(splitter)
# Initialize interface list
self.interfaces = get_network_interfaces()
self.interface_combo.addItems([i['name'] for i in self.interfaces])
# Connect signals
self.scan_button.clicked.connect(self.on_select_interface)
self.vuln_scan_button.clicked.connect(self.on_vulnerability_scan)
self.manual_scan_button.clicked.connect(self.on_manual_scan)
def load_scan_history(self):
try:
if os.path.exists(self.json_file_path):
with open(self.json_file_path, 'r') as f:
return json.load(f)
return []
except Exception as e:
print(f"Error loading scan history: {e}")
return []
def save_scan_results(self, scan_type, results):
try:
scan_data = {
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'scan_type': scan_type,
'results': results
}
self.scan_history.append(scan_data)
with open(self.json_file_path, 'w') as f:
json.dump(self.scan_history, f, indent=4)
except Exception as e:
QMessageBox.warning(self, "Save Error", f"Failed to save scan results: {str(e)}")
def on_select_interface(self):
selected_interface = self.interface_combo.currentText()
if not selected_interface:
QMessageBox.critical(self, "Error", "Please select an interface.")
return
for interface in self.interfaces:
if interface['name'] == selected_interface:
self.scan_button.setEnabled(False)
self.scan_button.setText("Scanning...")
network_ip = interface['ip']
subnet_mask = interface['subnet_mask']
network_prefix = f"{network_ip}/{ipaddress.IPv4Network(f'{network_ip}/{subnet_mask}', strict=False).prefixlen}"
self.scan_worker = ScanWorker(network_prefix)
self.scan_worker.finished.connect(self.on_scan_complete)
self.scan_worker.start()
break
def on_scan_complete(self, online_ips):
self.ip_list.clear()
if online_ips:
self.ip_list.addItems(online_ips)
# Save network scan results
self.save_scan_results('network_scan', {
'online_devices': online_ips
})
else:
QMessageBox.information(self, "No Devices", "No online devices found.")
self.scan_button.setEnabled(True)
self.scan_button.setText("Scan Network")
def on_vulnerability_scan(self):
selected_items = self.ip_list.selectedItems()
if not selected_items:
QMessageBox.critical(self, "Error", "Please select an IP address from the list.")
return
selected_ip = selected_items[0].text()
self.vuln_scan_button.setEnabled(False)
self.vuln_scan_button.setText("Scanning...")
self.vuln_worker = VulnScanWorker(selected_ip)
self.vuln_worker.finished.connect(self.on_vuln_scan_complete)
self.vuln_worker.start()
def on_vuln_scan_complete(self, device_details):
self.result_tree.clear()
scan_results = {
'operating_system': device_details['Operating System'],
'services': device_details['Services']
}
if device_details['Operating System']:
item = QTreeWidgetItem(["Operating System", device_details['Operating System'], ""])
self.result_tree.addTopLevelItem(item)
for service in device_details['Services']:
item = QTreeWidgetItem([
f"Port {service['Port']}",
service['Service'],
service['Version']
])
self.result_tree.addTopLevelItem(item)
# Save vulnerability scan results
self.save_scan_results('vulnerability_scan', scan_results)
self.vuln_scan_button.setEnabled(True)
self.vuln_scan_button.setText("Scan Vulnerabilities")
def on_manual_scan(self):
ip_range = self.ip_range_input.currentText().strip()
if not ip_range:
QMessageBox.critical(self, "Error", "Please enter an IP range.")
return
try:
# Validate IP range format
ipaddress.ip_network(ip_range, strict=False)
except ValueError as e:
QMessageBox.critical(self, "Error", f"Invalid IP range format: {str(e)}")
return
self.manual_scan_button.setEnabled(False)
self.manual_scan_button.setText("Scanning...")
self.scan_worker = ScanWorker(ip_range)
self.scan_worker.finished.connect(self.on_manual_scan_complete)
self.scan_worker.start()
def on_manual_scan_complete(self, online_ips):
self.ip_list.clear()
if online_ips:
self.ip_list.addItems(online_ips)
# Save manual scan results
self.save_scan_results('manual_scan', {
'online_devices': online_ips
})
else:
QMessageBox.information(self, "No Devices", "No online devices found in the specified range.")
self.manual_scan_button.setEnabled(True)
self.manual_scan_button.setText("Scan IP Range")
def main():
app = QApplication([])
window = MainWindow()
window.show()
app.exec()
if __name__ == "__main__":
main()