-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuser_settings.py
More file actions
486 lines (327 loc) · 16.4 KB
/
user_settings.py
File metadata and controls
486 lines (327 loc) · 16.4 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
475
476
477
478
479
480
481
482
483
# MODULE ONLY FOR USERT SETTING // SETTING JSON FILE # DEVELOPED BY NSM BARII
# WILL BE UPDATING THIS MODULE SOON
# UI IMPORTS
from rich.panel import Panel
from rich.table import Table
from rich.live import Live
from rich.console import Console
console = Console()
console_width = console.size.width
import pyfiglet
# CONSOLE OBJECTS
console = Console()
console_width = console.size.width
# ETC IMPORTS
import json, os, time, requests
# FILE PATH
from pathlib import Path
base_dir = Path.home() / "Documents" / "NSM Tools" / ".data" / "NetAlert2" / "settings"
base_dir.mkdir(parents=True, exist_ok=True)
# SETTINGS PATH
settings_path = base_dir / "settings.json"
class user_settings():
"""Primary and only responsibility of this class is to keep track of user data/settings!"""
def __init__(self):
self.file_user_settings = settings_path
def save_data(self, changed_data):
"""Responsible for saving user changed data // settings"""
# NOT NEEDED // BUT I WANTED A MORE COMPACT VARIABLE NAME
path = self.file_user_settings
indent = 10
try:
with open(path, "w") as file:
json.dump(changed_data, file, indent=indent)
#console.print("File successfully updated", style="bold green")
except FileNotFoundError as e:
self.create_file()
except Exception as e:
self.create_file() # PLACE THE ERROR IN CREATE FILE METHOD // TO MAKE TROUBLE SHOOTING EASIER!
def load_file(self):
# NOT NEEDED // BUT I WANTED A MORE COMPACT VARIABLE NAME
path = self.file_user_settings
# AFTER DEFAULT PATH IS CREATED LOOP BACK THROUGH THE TRY BLOCK
while True:
try:
with open(path, "r") as file:
content = json.load(file)
return content
except FileNotFoundError as e:
console.print("User filepath not found", style="bold red")
self.create_file()
except Exception as e:
self.create_file() # PLACE THE ERROR IN CREATE FILE TO MAKE TROUBLE SHOOTING EASIER
def create_file(self):
"""Responsible for creating user default file settings if they cant be found by the program"""
# NOT NEEDED // BUT I WANTED A MORE COMPACT VARIABLE NAME
path = self.file_user_settings
indent = 10
# THIS LOOP ENSURES THAT AFTER A EXCEPTION THE MAIN TRY CONDITION IS REATTEMPTED!
while True:
try:
# DEFAULT DATA
data = {
"display_name": "user",
"monitor_mode": False,
"background_thread": False,
"discord_webhook": False,
"intrusion_updates": False,
"rate_limit": 50,
"subnet_address": "",
"scan_interval": 15,
"monitor_mode_scans": 0
}
with open(path, "w") as file:
json.dump(data, file, indent = indent)
console.print("[bold green]Default File Path Successfully Created![/bold green]")
time.sleep(2)
break
# IN CASE USER FILE // JSON FILE IS CORRUPTED WE RESET IT BACK TO NORMAL
except json.JSONDecodeError as e:
data = {}
with open(path, "w") as file:
json.dump(data, file, indent=indent)
console.print("Corrupt File safetly fixed!", style="bold green")
time.sleep(1)
except Exception as e:
console.print(e)
Console.input("Please restart the program to attempt to fix the issue: ")
# THIS WILL NOT WORK IN EXE // NOT RECOMMENDED BUT WILL USE FOR NOW
exit()
class settings_menu():
"""here is where all the settings functionality code will be placed"""
def __init__(self):
self.loops = 0
pass
def settings(self):
"""Settings module that encapsulates all other settings options"""
while True:
# CREATE LOAD & SAVE OBJECTS
data = user_settings()
load = data.load_file()
# CREATE CLEAR SCREEN OBJECT
cls = extra_shii()
cls.clear_screen()
welcome = pyfiglet.figlet_format("Settings")
welcomejr = ""
console.print(f"[bold red]{welcome}[/bold red]")
console.print(load["display_name"])
# DISPLAY CURRENT SETTING // MORE FLEXIBLE SETTINGS MODULE
console.print(f"\n[bold red]----- Current Settings -----[/bold red]\n")
for variable, value in load.items():
console.print(f"[bold green]{variable}[/bold green] --> [bold blue]{value}[/bold blue]")
console.print("\n[bold red]------------------------------[/bold red]\n")
options = Panel(
"1. Display name\n\n"
"2. Discord Webhook\n"
"3. Intrusion Updates\n"
"4. Subnet Address\n"
"5. Scan Interval\n"
"6. Rate Limit"
"\n7. Exit",
title="Options",
style="red",
border_style="bold red",
width=min(130, console_width - 2)
)
console.print(options)
choice = console.input("\n\n[bold blue]Enter your choice here: [/bold blue]")
# DISPLAY NAME
if choice == "1":
# INITIATE AT THE BEGINNING OF EACH BLOCK TO REFRESH AND GET THE MOST UP TO DATE SETTINGS
data = user_settings()
load = data.load_file()
change = console.input("[bold blue]Enter new display name: [bold blue]")
# CALL UPON LOAD METHOD TO SAVE SETTINGS
load["display_name"] = change
data.save_data(changed_data=load)
# DISCORD WEBHOOD
elif choice == "2":
# INITIATE AT THE BEGINNING OF EACH BLOCK TO REFRESH AND GET THE MOST UP TO DATE SETTINGS
data = user_settings()
load = data.load_file()
try:
# USER INPUTS THERE DISCORD WEBHOOK
webhook_url = console.input("[bold blue]Enter Discord Webhook: [/bold blue]")
data = {
"content":
"Message: Hey there I am necessary to protect your network.\nAny and all threats will be destroyed!",
"username": "Intrusion Protection BOT"
}
response = requests.post(webhook_url, data=json.dumps(data), headers={"content-type": "application/json"})
# CHECK IF WEBHOOK IS VALID
if response.status_code == 204:
# NOW TO SAVE WEBHOOK
data = user_settings()
load = data.load_file()
load["discord_webhook"] = webhook_url
data.save_data(changed_data=load)
console.print("[bold green]Discord Webhook Successfully Updated![/bold green]")
time.sleep(1.5)
else:
console.print(f"Invalid Webhook given please try again: {webhook_url}")
time.sleep(1.5)
# ERROR HANDLING
except requests.ConnectionError as e:
console.print(f"[bold red]Connection Error:[/bold red][yellow]{e}[/yellow]")
time.sleep(1.5)
except requests.JSONDecodeError as e:
console.print(f"[bold red]JSON Error:[/bold red][yellow]{e}[/yellow]")
time.sleep(1.5)
except Exception as e:
console.print(f"[bold red]Unkown Exception Error:[/bold red][yellow]{e}[/yellow]")
time.sleep(1.5)
# INTRUSION UPDATES
elif choice == "3":
while True:
change = console.input("[yellow]Do you want to turn Intrustion Updates[/yellow] [bold green]On[/bold green] [yellow]or[/yellow] [bold red]Off[/bold red]: ").lower()
if change == "on":
# CHANGE VARIABLE TO TRUE
data = user_settings()
load = data.load_file()
load["intrusion_updates"] = True
data.save_data(changed_data=load)
break
elif change == "off":
# CHANGE VARIABLE TO FALSE
data = user_settings()
load = data.load_file()
load["intrusion_updates"] = False
data.save_data(changed_data=load)
break
else:
console.print(f"[bold red]{change}[/bold red] [yellow]is a invalid choice, please Try again[/yellow]")
console.print(f"[bold blue]Settings Successfully Updated - Intrusion Updates are now:[/bold blue][bold green] {change}[/bold green]")
time.sleep(1.5)
# IP SUBNET
elif choice == "4":
import ipaddress
while True:
try:
subnet = console.input("[bold blue]Enter Network Range:[/bold blue] ")
valid_subnet = ipaddress.ip_network(subnet, strict=False)
valid_subnet = str(valid_subnet)
# NOW TO SAVE SUBNET
data = user_settings()
load = data.load_file()
load["subnet_address"] = valid_subnet
data.save_data(changed_data=load)
console.print(f"[bold green]IP Subnet:{valid_subnet} Successfully Updated![/bold green]")
time.sleep(1.8)
break
except ipaddress.AddressValueError as e:
console.print(e)
except ipaddress.NetmaskValueError as e:
console.print(e)
except Exception as e:
console.print(e)
# SCAN INTERVAL
elif choice == "5":
interval = console.input("[bold blue]Enter scan interval timer in minutes: [/bold blue]")
# NOW TO SAVE TIMER INTERVAL
data = user_settings()
load = data.load_file()
load["scan_interval"] = interval
data.save_data(changed_data=load)
console.print(f"[bold green]Scan interval Successfully Updated to perform a scan every: {interval} Minutes[/bold green]")
time.sleep(1.8)
elif choice == "6":
# SET VARIABLES
error = False
error_code = 0
print("\n")
while True:
if error:
if error_code == 1:
console.print(f"\n[bold red]Give a valid Integer goofy[/bold red]")
elif error_code == 2:
console.print(e)
try:
error = False
error_code = 0
rate_limit = console.input("[bold blue]Enter Rate limit:[/bold blue] ")
valid_rate_limit = int(rate_limit)
# NOW TO SAVE THE CHANGED DATA
load = user_settings().load_file()
load["rate_limit"] = valid_rate_limit
user_settings().save_data(changed_data=load)
break
except ValueError as e:
error = True
error_code = 1
except Exception as e:
error = True
error_code = 2
# EXIT BACK TO MAIN MENU
elif choice == "7":
break
# INCORRECT CHOICE
else:
console.print(f"Invalid option, please try again with options(1-7)")
time.sleep(1.5)
def not_in_use(self):
"""Options for settings menu that are no longer or currently not in use"""
choice = ""
# LIVE UPDATES
if choice == "3":
while True:
change = console.input("[yellow]Do you want to turn Live Updates[/yellow] [bold green]On[/bold green] [yellow]or[/yellow] [bold red]Off[/bold red]: ")
if change == "on":
# CHANGE VARIABLE TO TRUE
data = user_settings()
load = data.load_file()
load["live_updates"] = True
data.save_data(changed_data=load)
break
elif change == "off":
# CHANGE VARIABLE TO FALSE
data = user_settings()
load = data.load_file()
load["live_updates"] = False
data.save_data(changed_data=load)
break
else:
console.print(f"[bold red]{change}[/bold red] [yellow]is a invalid choice, please Try again[/yellow]")
console.print(f"[bold blue]Settings Successfully Updated - Live Updates are now:[/bold blue][bold green] {change}[/bold green]")
time.sleep(1.5)
# CONTINOUS MONITORING
if choice == "5":
while True:
change = console.input("[yellow]Do you want to turn Continous Monitoring[/yellow] [bold green]On[/bold green] [yellow]or[/yellow] [bold red]Off[/bold red]: ")
if change == "on":
# CHANGE VARIABLE TO TRUE
data = user_settings()
load = data.load_file()
load["continous_monitoring"] = True
data.save_data(changed_data=load)
break
elif change == "off":
# CHANGE VARIABLE TO FALSE
data = user_settings()
load = data.load_file()
load["continous_monitoring"] = False
data.save_data(changed_data=load)
break
else:
console.print(f"[bold red]{change}[/bold red] [yellow]is a invalid choice, please Try again[/yellow]")
console.print(f"[bold blue]Settings Successfully Updated - Continous Monitoring is now set to:[/bold blue][bold green] {change}[/bold green]")
time.sleep(1.5)
class extra_shii():
"""Clear screen for settings modules"""
def __init__(self):
pass
def clear_screen(self):
"""Clear screen"""
if os.name == "nt":
os.system("cls")
else:
os.system("clear")
if __name__ == "__main__":
nsm = settings_menu()
nsm.settings()
# 5. Settings
# 1. Change display name
# 2. Discord Webhook
# 3. Live updates
# 4. Intrusion Updates
# 5. Continous Monitoring
#