-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnet_adap_profiles.py
742 lines (582 loc) · 25.8 KB
/
net_adap_profiles.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
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
"""Manage profiles including the necessary widgets"""
import json
import os
import re
import traceback
import tkinter as tk
from tkinter import filedialog
import ttkbootstrap as ttk
from ttkbootstrap.toast import ToastNotification
from ttkbootstrap.dialogs.dialogs import MessageDialog, Messagebox
from network_adapters import NetworkAdapters
import preferences as pref
APPNAME = "Sinamawin"
class NetAdapProfiles:
"""Management of network adapter profiles"""
def __init__(self, ip: str = "", mask: str = "255.255.255.0",
gateway: str = "0.0.0.0", pref_dns: str = "",
alt_dns: str = "", name: str = "") -> None:
self.name = name
self.ip = ip
self.mask = mask
self.gateway = gateway
self.pref_dns = pref_dns
self.alt_dns = alt_dns
self._manage_prof_popup = None # Manage profile popup
self._return = None # Return data
def delete_profile(self, name: str) -> None:
"""Delete a profile from the profile file.
Args:
name (str): Profile name to be deleted.
"""
profiles = self.get_profiles()
del profiles[name]
if self.save_profiles(profiles):
self.toast_notification(f"Profile '{name}' successfully deleted.")
def export_profiles(self, parent: ttk.Toplevel = None) -> None:
"""Export profiles to a CSV file.
Args:
parent (ttk.Toplevel, optional): Parent window. Defaults to None.
"""
popup = ttk.Toplevel(title=f"{APPNAME} - Export profiles to CSV",
resizable=(False, False))
profiles = self.get_profiles()
preferences = pref.get_preferences()
# Delimiter
delimiter = ";"
if "delimiter" in preferences:
delimiter = preferences["delimiter"]
l_delimiter = ttk.Label(popup, text="Delimiter:")
e_delimiter = ttk.Entry(popup, width=15, justify="center")
e_delimiter.insert(0, delimiter)
l_delimiter.grid(row=0, column=0, padx=(15, 5), pady=15)
e_delimiter.grid(row=0, column=1, padx=(5, 15), pady=15)
# Save button
def save_btn():
delimiter = e_delimiter.get()
dest_file = filedialog.asksaveasfilename(
title=f"{APPNAME} - Select destination folder",
filetypes=(("CSV", ".csv"), ("All files", "*.*")),
initialfile="Sinamawin_Profiles.csv"
)
headers = ["Name", "IP", "Subnet mask", "Default gateway",
"Preferred DNS Server", "Alternate DNS Server"]
with open(dest_file, "w", encoding="utf-8") as fdest:
fdest.write(f"{str(delimiter)}".join(headers) + "\n")
for name, data in profiles.items():
info = [str(name)]
info.append(data["ip"])
info.append(data["mask"])
info.append(data["gateway"])
info.append(data["pref_dns"])
info.append(data["alt_dns"])
fdest.write(f"{str(delimiter)}".join(info) + "\n")
preferences["delimiter"] = delimiter
pref.save_preferences(preferences)
self.toast_notification("Profiles successfully exported.")
popup.destroy()
if parent:
# Refresh the window
parent.destroy()
self.manage_profiles()
b_save = ttk.Button(popup,
text="Save", width=8,
command=save_btn)
b_save.grid(row=1, column=1, padx=(5, 15), pady=(5, 15), sticky="e")
# Mouse wheel behavior
def popup_window_scroll(_):
"""To avoid propagating the event to the main window."""
return "break"
popup.bind("<MouseWheel>", popup_window_scroll)
return
def get_profiles(self) -> dict:
"""Get profiles from the profile file.
Returns:
dict: All saved profiles.
"""
profiles = {}
prof_path = os.environ.get(f"{APPNAME}_PROFILES")
if os.path.exists(prof_path):
with open(prof_path, "r", encoding="utf-8") as file:
profiles = json.load(file)
return profiles
def import_profiles(self, parent: ttk.Toplevel = None) -> None:
"""Import profiles from a CSV file. If a profile name already
exists, it will be saved as "name_[X]".
Args:
parent (ttk.Toplevel, optional): Parent window. Defaults to None.
"""
src_file = filedialog.askopenfilename(
title=f"{APPNAME} - Import profiles from CSV",
filetypes=(("CSV", ".csv"), ("All files", "*.*"))
)
popup = ttk.Toplevel(title=f"{APPNAME} - Import profiles from CSV",
resizable=(False, False))
preferences = pref.get_preferences()
# Delimiter
delimiter = ";"
if "delimiter" in preferences:
delimiter = preferences["delimiter"]
msg = ("The profiles will be added to the existing ones."
"\nIf duplicates exist, both will be maintained.")
l_info = ttk.Label(popup, text=msg)
l_info.grid(row=0, column=0, columnspan=2, padx=15, pady=15)
l_delimiter = ttk.Label(popup, text="Delimiter:")
e_delimiter = ttk.Entry(popup, width=15, justify="center")
e_delimiter.insert(0, delimiter)
l_delimiter.grid(row=1, column=0, padx=(15, 5), pady=15, sticky="e")
e_delimiter.grid(row=1, column=1, padx=(5, 15), pady=15, sticky="e")
# Import button
def import_prof():
try:
profiles = self.get_profiles()
delimiter = e_delimiter.get()
with open(src_file, "r", encoding="utf-8") as file:
for line in list(file)[1:]:
data = line.replace("\n", "").split(delimiter)
name, ip, mask, gateway, pref_dns, alt_dns = data
ctrl = 2
aux_name = name
while str(name) in profiles:
name = f"{aux_name}_{ctrl}"
ctrl += 1
name = re.sub(r"[^\w\s\-]", "", name)
na = NetworkAdapters()
if not (na.validate_ipv4(ip)
or na.validate_subnet_mask(mask)):
raise ValueError()
if gateway == "":
gateway = "0.0.0.0"
elif not na.validate_ipv4(gateway):
raise ValueError()
if pref_dns and not na.validate_ipv4(pref_dns):
raise ValueError()
if alt_dns and not na.validate_ipv4(alt_dns):
raise ValueError()
profiles[name] = {
"ip": str(ip),
"mask": str(mask),
"gateway": str(gateway),
"pref_dns": str(pref_dns),
"alt_dns": str(alt_dns),
}
if self.save_profiles(profiles):
self.toast_notification("Profile successfully imported.")
else:
raise NotImplementedError()
except: # pylint: disable=bare-except # noqa
Messagebox.show_error(
message=("The file could not be imported."
"\nCheck and try again."),
title=f"{APPNAME} - Error",
padding=(30, 30),
width=100,
parent=parent)
popup.destroy()
return
preferences["delimiter"] = delimiter
pref.save_preferences(preferences)
popup.destroy()
if parent:
# Refresh the window
parent.destroy()
self.manage_profiles()
b_import = ttk.Button(popup,
text="Import", width=8,
command=import_prof)
b_import.grid(row=2, column=1, padx=(5, 15), pady=(5, 15), sticky="e")
# Mouse wheel behavior
def popup_window_scroll(_):
"""To avoid propagating the event to the main window."""
return "break"
popup.bind("<MouseWheel>", popup_window_scroll)
return
def manage_profiles(self, select: bool = False) -> dict:
"""Displays a window for managing profiles.
Args:
select (bool, optional): If True displays "Select" and
"Select & Apply" buttons instead of "New", "Edit" and
"Delete" buttons. Defaults to False.
Returns:
dict: Return the selected profile.
"""
self._manage_prof_popup = None
popup = ttk.Toplevel(title=f"{APPNAME} - Manage profiles",
resizable=(False, False),
size=(760, 250))
prof_table = ttk.Treeview(popup)
prof_table["columns"] = (
"NAME", "IP", "SUBNET_MASK", "GATEWAY", "PREF_DNS", "ALT_DNS")
# Configure the style of heading in the table
prof_table_style = ttk.Style()
prof_table_style.configure('Treeview.Heading',
background="#C4790E",
foreground="white",
font=('Arial', 8, 'bold'))
prof_table_style.configure('Treeview',
rowheight=25
)
# Configure columns
prof_table.column("#0", anchor="center", width=0, stretch=False)
for column in prof_table["columns"]:
prof_table.column(column, stretch=False,
anchor="center", width=120)
prof_table.heading(column, text=column, anchor="center")
# Scrollbar
scrollbar = ttk.Scrollbar(
popup, bootstyle="primary-round", orient="vertical",
command=prof_table.yview)
scrollbar.grid(row=0, column=5, sticky="ns", padx=(5, 10))
prof_table.configure(yscrollcommand=scrollbar.set)
# Add profiles to the table
profiles = self.get_profiles()
for index, (name, data) in enumerate(profiles.items()):
prof_table.insert(parent="", index="end", iid=index, text="",
values=(name,
data["ip"],
data["mask"],
data["gateway"],
data["pref_dns"],
data["alt_dns"]
))
prof_table.grid(row=0, column=0, columnspan=5, sticky="nsew")
# Functions that provide utility to the buttons
def get_selected_row(show_error: bool = True) -> str:
"""Gets the row selected by the user.
Args:
show_error (bool, optional): If True displays an error message
if the user has not selected any rows. Defaults to True.
Returns:
str: Name of the selected profile.
"""
selection = prof_table.selection()
name = ""
if selection:
self._manage_prof_popup = popup
name = list(profiles.keys())[int(selection[0])]
elif show_error:
Messagebox.show_error(
message="No row is selected.",
title=f"{APPNAME} - Error",
padding=(30, 30),
width=100)
return name
def new_profile() -> None:
"""Open a pop-up window to save a new profile.
If one is selected, copy the information.
"""
name = get_selected_row(show_error=False)
self.name = ""
self.ip = profiles[name]["ip"] if name else ""
self.mask = profiles[name]["mask"] if name else "255.255.255.0"
self.gateway = profiles[name]["gateway"] if name else "0.0.0.0"
self.pref_dns = profiles[name]["pref_dns"] if name else ""
self.alt_dns = profiles[name]["alt_dns"] if name else ""
self._manage_prof_popup = popup
self.save_profile_popup(remove=self.name)
return
def edit_profile() -> None:
"""Open a pop-up window to edit a profile's information."""
name = get_selected_row()
if not name:
return
self.name = name
self.ip = profiles[name]["ip"]
self.mask = profiles[name]["mask"]
self.gateway = profiles[name]["gateway"]
self.pref_dns = profiles[name]["pref_dns"]
self.alt_dns = profiles[name]["alt_dns"]
self._manage_prof_popup = popup
self.save_profile_popup(f"Edit profile '{name}'", remove=self.name)
return
def delete_profile() -> None:
"""Delete a profile by requesting confirmation from the user."""
name = get_selected_row()
if not name:
return
msg = f"Do you want to remove the profile '{name}'?"
dialog_title = f"{APPNAME} - Remove {name}"
dialog = MessageDialog(message=msg,
title=dialog_title,
buttons=["Accept", "Cancel"],
padding=(30, 30),
width=70)
dialog.show()
if dialog.result == "Accept":
self.delete_profile(name)
# Refresh the window
popup.destroy()
self.manage_profiles()
def select_apply_profile(apply: bool = False) -> None:
"""'Select' or 'Select & Apply' a profile.
Args:
apply (bool, optional): Indicate whether "Select" (False) or
"Select and Apply" (True). Defaults to False.
"""
name = get_selected_row()
if not name:
return
self._return = {
"name": name,
"ip": profiles[name]["ip"],
"mask": profiles[name]["mask"],
"gateway": profiles[name]["gateway"],
"pref_dns": profiles[name]["pref_dns"],
"alt_dns": profiles[name]["alt_dns"],
"apply": apply
}
# Destroy the popup window
popup.destroy()
# Buttons
if select: # "Select" and "Select & Apply"
b_select = ttk.Button(popup, text="Select",
command=select_apply_profile)
b_sel_apply = ttk.Button(
popup, text="Select & Apply",
command=lambda: select_apply_profile(True))
b_select.grid(row=1, column=1, padx=5, pady=10)
b_sel_apply.grid(row=1, column=2, padx=5, pady=10)
else: # "New", "Edit" and "Delete"
b_export = ttk.Button(popup, text="Export",
bootstyle="secondary",
command=lambda: self.export_profiles(popup))
b_import = ttk.Button(popup, text="Import",
bootstyle="secondary",
command=lambda: self.import_profiles(popup))
b_new = ttk.Button(popup, text="New",
command=new_profile)
b_edit = ttk.Button(popup, text="Edit",
bootstyle="dark", command=edit_profile)
b_remove = ttk.Button(popup, text="Delete",
bootstyle="danger",
command=delete_profile)
b_export.grid(row=1, column=0, padx=5, pady=10, sticky="e")
b_import.grid(row=1, column=1, padx=5, pady=10)
b_new.grid(row=1, column=2, padx=5, pady=10)
b_edit.grid(row=1, column=3, padx=5, pady=10)
b_remove.grid(row=1, column=4, padx=5, pady=10)
# Adjust size of columns to window size
popup.grid_columnconfigure(0, weight=1)
popup.grid_rowconfigure(0, weight=1)
# Mouse wheel behavior
def popup_window_scroll(_):
"""To avoid propagating the event to the main window."""
scrollbar.set(*prof_table.yview())
return "break"
popup.bind("<MouseWheel>", popup_window_scroll)
# Wait until the popup window is destroyed
popup.wait_window()
return self._return
def save_profile(self, popup: ttk.Toplevel = None,
remove: str = "") -> None:
"""Validate that the profile is valid and save it in the profile file.
Args:
popup (ttk.Toplevel, optional): Raise the window in the stack of
window and destroys the window at the end. Defaults to None.
remove (str, optional): Name of the profile to be deleted,
replaced by the new one. Defaults to "".
"""
try:
# Remove characters not allowed
self.name = re.sub(r"[^\w\s\-]", "", self.name)
ni = NetworkAdapters()
def show_error(msg):
Messagebox.show_error(
message=msg,
title=f"{APPNAME} - Invalid data",
padding=(30, 30),
width=100)
if popup:
# Raise the window in the stack of windows
popup.lift()
if not self.name or not self.name.isascii():
show_error("Invalid profile name.")
return
if not ni.validate_ipv4(self.ip):
show_error("Invalid IP address.")
return
if not ni.validate_subnet_mask(self.mask):
show_error("Invalid subnet mask.")
return
if self.gateway == "":
self.gateway = "0.0.0.0"
elif not ni.validate_ipv4(self.gateway):
show_error("Invalid default gateway.")
return
if self.pref_dns and not ni.validate_ipv4(self.pref_dns):
show_error("Invalid preferred DNS server.")
return
if self.alt_dns and not ni.validate_ipv4(self.alt_dns):
show_error("Invalid alternate DNS server.")
return
if self.pref_dns and self.pref_dns == self.alt_dns:
show_error(
"The preferred and alternate"
" DNS servers can not be the same.")
return
if not self.pref_dns and self.alt_dns:
self.pref_dns = self.alt_dns
self.alt_dns = ""
profiles = self.get_profiles()
new_profile = {
"ip": self.ip,
"mask": self.mask,
"gateway": self.gateway,
"pref_dns": self.pref_dns,
"alt_dns": self.alt_dns
}
if profiles and self.name in list(profiles.keys()):
msg = (f"The profile '{self.name}' already exists."
" Do you want to replace it with the new one?")
dialog_title = f"{APPNAME} - Duplicate profile name"
dialog = MessageDialog(message=msg,
title=dialog_title,
buttons=["Accept", "Cancel"],
padding=(30, 30),
width=70)
dialog.show()
if dialog.result == "Accept":
profiles[self.name] = new_profile
# Remove the old profile
if remove and remove != self.name:
del profiles[remove]
else:
return
else:
profiles[self.name] = new_profile
# Remove the old profile
if remove:
del profiles[remove]
if self.save_profiles(profiles):
self.toast_notification("Profile saved successfully.")
if popup:
popup.destroy()
# Refresh the window
if self._manage_prof_popup:
self._manage_prof_popup.destroy()
self.manage_profiles()
return
except: # pylint: disable=bare-except # noqa
traceback.print_exc()
Messagebox.show_error(
message="The profile could not be saved.",
title=f"{APPNAME} - Error",
padding=(30, 30),
width=100)
def save_profile_popup(self, title: str = "New profile",
remove: str = "") -> None:
"""Window to save/edit the profile information.
Args:
title (str, optional): Title of the window.Defaults to
"New profile".
remove (str, optional): Profile name to be deleted. Defaults to "".
"""
popup = ttk.Toplevel(title=f"{APPNAME} - {title}",
resizable=(False, False))
# ---------
# | ROW 0 |
# ---------
l_name = ttk.Label(popup, text="Profile name:",
font=("Arial", 9, "bold"))
d_name = ttk.Entry(
popup, width=30, justify="left")
if self.name:
d_name.insert(0, self.name)
l_name.grid(row=0, column=0, padx=(25, 5), pady=(15, 5))
d_name.grid(row=0, column=1, padx=5, pady=(15, 5))
# ---------
# | ROW 1 |
# ---------
# -- IP address --
l_ip_addr = ttk.Label(popup, text="IP address:")
d_ip_addr = ttk.Entry(
popup, width=15, justify="center")
d_ip_addr.insert(0, self.ip)
l_ip_addr.grid(row=1, column=0, padx=(25, 5), pady=5)
d_ip_addr.grid(row=1, column=1, padx=5, pady=5)
# -- Subnet mask --
l_subnet = ttk.Label(popup, text="Subnet mask:")
d_subnet = ttk.Entry(
popup, width=15, justify="center")
d_subnet.insert(0, self.mask)
l_subnet.grid(row=1, column=2, padx=(15, 5), pady=5)
d_subnet.grid(row=1, column=3, padx=5, pady=5)
# -- Default gateway --
l_gateway = ttk.Label(popup, text="Default gateway:")
d_gateway = ttk.Entry(
popup, width=15, justify="center")
d_gateway.insert(0, self.gateway)
l_gateway.grid(row=1, column=4, padx=(15, 5), pady=5)
d_gateway.grid(row=1, column=5, padx=(5, 25), pady=5)
# ---------
# | ROW 2 |
# ---------
# -- Preferred DNS Server --
l_pref_dns_server = ttk.Label(
popup, text="Preferred DNS Server:")
d_pref_dns_server = ttk.Entry(
popup, width=15, justify="center")
d_pref_dns_server.insert(0, self.pref_dns)
l_pref_dns_server.grid(row=2, column=0, padx=(25, 5), pady=5)
d_pref_dns_server.grid(row=2, column=1, padx=5, pady=5)
# -- Alternate DNS Server --
l_alt_dns_server = ttk.Label(
popup, text="Alternate DNS Server:")
d_alt_dns_server = ttk.Entry(
popup, width=15, justify="center")
d_alt_dns_server.insert(0, self.alt_dns)
l_alt_dns_server.grid(row=2, column=2, padx=(15, 5), pady=5)
d_alt_dns_server.grid(row=2, column=3, padx=5, pady=5)
# ---------
# | ROW 3 |
# ---------
def clear_entries():
d_name.delete(0, tk.END)
d_ip_addr.delete(0, tk.END)
d_subnet.delete(0, tk.END)
d_subnet.insert(0, "255.255.255.0")
d_gateway.delete(0, tk.END)
d_gateway.insert(0, "0.0.0.0")
d_pref_dns_server.delete(0, tk.END)
d_alt_dns_server.delete(0, tk.END)
def save_profile_data():
self.name = d_name.get().strip()
self.ip = d_ip_addr.get()
self.mask = d_subnet.get()
self.gateway = d_gateway.get()
self.pref_dns = d_pref_dns_server.get()
self.alt_dns = d_alt_dns_server.get()
self.save_profile(popup, remove)
b_clear = ttk.Button(popup, bootstyle="warning", text="Clear",
width=10, command=clear_entries)
b_save = ttk.Button(popup, text="Save", width=10,
command=save_profile_data)
b_cancel = ttk.Button(popup, bootstyle="dark",
text="Cancel", command=popup.destroy, width=10)
b_clear.grid(row=3, column=0, padx=5, pady=(5, 25))
b_save.grid(row=3, column=4, padx=5, pady=(5, 25), sticky="e")
b_cancel.grid(row=3, column=5, padx=5, pady=(5, 25))
def save_profiles(self, profiles: dict) -> bool:
"""Save the profiles in the profile file.
Args:
profiles (dict): Profiles to be saved.
Returns:
bool: True if saved.
"""
with open(os.environ.get(f"{APPNAME}_PROFILES"), "w",
encoding="utf-8") as file:
json.dump(dict(sorted(profiles.items())), file, indent=4)
return True
def toast_notification(self, toast_msg: str) -> None:
"""Display a notification toast with a message.
Args:
toast_msg (str): Message to be displayed.
"""
toast = ToastNotification(
title=APPNAME,
message=toast_msg,
duration=5000,
icon="\u2714"
)
toast.show_toast()
return