add con_to_dict in import for write PreSharedKey in .key File to warning if tunnel has already been imported and delete that the key is deleted again

This commit is contained in:
Désiré Werner Menrath 2024-09-22 00:56:08 +02:00
parent 53f1d4e8f4
commit f90b10f948
3 changed files with 83 additions and 47 deletions

View File

@ -4,7 +4,7 @@
<option name="autoReloadType" value="SELECTIVE" /> <option name="autoReloadType" value="SELECTIVE" />
</component> </component>
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="940e1630-c825-4d4c-be80-bc11f543c122" name="Changes" comment="chown Export File to 1000:1000"> <list default="true" id="940e1630-c825-4d4c-be80-bc11f543c122" name="Changes" comment="add rename Label rename works">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/wg_func.py" beforeDir="false" afterPath="$PROJECT_DIR$/wg_func.py" afterDir="false" /> <change beforePath="$PROJECT_DIR$/wg_func.py" beforeDir="false" afterPath="$PROJECT_DIR$/wg_func.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/wg_main.py" beforeDir="false" afterPath="$PROJECT_DIR$/wg_main.py" afterDir="false" /> <change beforePath="$PROJECT_DIR$/wg_main.py" beforeDir="false" afterPath="$PROJECT_DIR$/wg_main.py" afterDir="false" />
@ -478,7 +478,15 @@
<option name="project" value="LOCAL" /> <option name="project" value="LOCAL" />
<updated>1726860371820</updated> <updated>1726860371820</updated>
</task> </task>
<option name="localTasksCounter" value="44" /> <task id="LOCAL-00044" summary="add rename Label rename works">
<option name="closed" value="true" />
<created>1726915238475</created>
<option name="number" value="00044" />
<option name="presentableId" value="LOCAL-00044" />
<option name="project" value="LOCAL" />
<updated>1726915238475</updated>
</task>
<option name="localTasksCounter" value="45" />
<servers /> <servers />
</component> </component>
<component name="UnknownFeatures"> <component name="UnknownFeatures">
@ -519,7 +527,6 @@
</component> </component>
<component name="VcsManagerConfiguration"> <component name="VcsManagerConfiguration">
<option name="ADD_EXTERNAL_FILES_SILENTLY" value="true" /> <option name="ADD_EXTERNAL_FILES_SILENTLY" value="true" />
<MESSAGE value="fix when Filname &gt; 17 first copy file after rename" />
<MESSAGE value="add export Tunnel as zip" /> <MESSAGE value="add export Tunnel as zip" />
<MESSAGE value="columnconfigure on all widgets set" /> <MESSAGE value="columnconfigure on all widgets set" />
<MESSAGE value="little fixes a &quot; &quot; to ' '" /> <MESSAGE value="little fixes a &quot; &quot; to ' '" />
@ -544,6 +551,7 @@
<MESSAGE value="replace tar with zip and Check if Zip file is empty" /> <MESSAGE value="replace tar with zip and Check if Zip file is empty" />
<MESSAGE value="Create your own message boxes for export" /> <MESSAGE value="Create your own message boxes for export" />
<MESSAGE value="chown Export File to 1000:1000" /> <MESSAGE value="chown Export File to 1000:1000" />
<option name="LAST_COMMIT_MESSAGE" value="chown Export File to 1000:1000" /> <MESSAGE value="add rename Label rename works" />
<option name="LAST_COMMIT_MESSAGE" value="add rename Label rename works" />
</component> </component>
</project> </project>

View File

@ -1,6 +1,7 @@
# Wireguard functions for Wire-Py # Wireguard functions for Wire-Py
import os import os
import shutil import shutil
import subprocess
import zipfile import zipfile
from datetime import datetime from datetime import datetime
from tkinter import filedialog, ttk from tkinter import filedialog, ttk
@ -156,7 +157,11 @@ class ConToDict:
if ',' in dns: if ',' in dns:
dns = dns[:-1] dns = dns[:-1]
endpoint = final_dict['Endpoint'] endpoint = final_dict['Endpoint']
return address, dns, endpoint if 'PresharedKey' in final_dict:
pre_key = final_dict['PresharedKey']
else:
pre_key = final_dict['PreSharedKey']
return address, dns, endpoint, pre_key
class TunnelActiv: class TunnelActiv:
@ -242,23 +247,37 @@ class ImportTunnel:
path_split1 = path_split[-1] path_split1 = path_split[-1]
self.a = TunnelActiv.active() self.a = TunnelActiv.active()
if 'PrivateKey = ' in read and 'PublicKey = ' in read: if 'PrivateKey = ' in read and 'PublicKey = ' in read:
with open(filepath, 'r') as file:
key = ConToDict.covert_to_dict(file)
pre_key = key[3]
print(type(pre_key))
if len(pre_key) != 0:
with open('/etc/wire_py/.keys', 'r') as readfile:
if pre_key in readfile:
print('Tunnel already available! Please use another file for import')
else:
with open('/etc/wire_py/.keys', 'a') as keyfile:
keyfile.write('\r\n' + pre_key)
if len(path_split1) > 17: if len(path_split1) > 17:
p1 = shutil.copy(filepath, Path('/etc/wire_py/')) p1 = shutil.copy(filepath, Path('/etc/wire_py/'))
path_split = path_split1[len(path_split1) - 17:] path_split = path_split1[len(path_split1) - 17:]
os.rename(p1, Path('/etc/wire_py') / str(path_split)) os.rename(p1, Path('/etc/wire_py') / str(path_split))
new_conf = '/etc/wire_py/' + path_split
if self.a != '': if self.a != '':
check_call(['nmcli', 'connection', 'down', TunnelActiv.active()]) check_call(['nmcli', 'connection', 'down', TunnelActiv.active()])
ShowAddress.label_empty(self) ShowAddress.label_empty(self)
check_call(['nmcli', 'connection', 'import', 'type', 'wireguard', 'file', Path('/etc') / 'wire_py' /
path_split]) subprocess.check_output(['nmcli', 'connection', 'import', 'type',
'wireguard', 'file', new_conf], text=True)
else: else:
shutil.copy(filepath, Path('/etc/wire_py/')) shutil.copy(filepath, Path('/etc/wire_py/'))
if self.a != '': if self.a != '':
check_call(['nmcli', 'connection', 'down', TunnelActiv.active()]) check_call(['nmcli', 'connection', 'down', TunnelActiv.active()])
ShowAddress.label_empty(self) ShowAddress.label_empty(self)
check_call(['nmcli', 'connection', 'import', 'type', 'wireguard', 'file', filepath])
subprocess.check_output(['nmcli', 'connection', 'import', 'type',
'wireguard', 'file', filepath], text=True)
self.StrVar.set('') self.StrVar.set('')
self.a = TunnelActiv.active() self.a = TunnelActiv.active()
@ -269,13 +288,14 @@ class ImportTunnel:
GreenLabel.green_show_label(self) GreenLabel.green_show_label(self)
StartStopBTN.button_stop(self) StartStopBTN.button_stop(self)
wg_read = Path('/etc/wire_py') / str(self.a + '.conf') wg_read = Path('/etc/wire_py') / str(self.a + '.conf')
with open(wg_read, 'r') as file: with open(wg_read, 'r') as file_for_key:
data = ConToDict.covert_to_dict(file) data = ConToDict.covert_to_dict(file_for_key)
# Address Label # Address Label
ShowAddress.init_and_report(self, data) ShowAddress.init_and_report(self, data)
ShowAddress.show_data(self) ShowAddress.show_data(self)
check_call(['nmcli', 'con', 'mod', self.a, 'connection.autoconnect', 'no']) check_call(['nmcli', 'con', 'mod', self.a, 'connection.autoconnect', 'no'])
os.chmod(str(wg_read), 0o600) os.chmod(str(wg_read), 0o600)
if 'PrivateKey = ' not in read: if 'PrivateKey = ' not in read:
msg_window() msg_window()
except EOFError: except EOFError:
@ -284,6 +304,8 @@ class ImportTunnel:
pass pass
except FileNotFoundError: except FileNotFoundError:
pass pass
except subprocess.CalledProcessError:
print('Tunnel exist!')
class FileHandle: class FileHandle:
@ -363,6 +385,3 @@ class ExportTunnels:
except TypeError: except TypeError:
pass pass

View File

@ -1,4 +1,5 @@
#!/usr/bin/python3 #!/usr/bin/python3
import os
import tkinter as tk import tkinter as tk
from subprocess import check_call from subprocess import check_call
from tkinter import * from tkinter import *
@ -18,7 +19,7 @@ class MainWindow(tk.Tk):
self.switch_on = None self.switch_on = None
self.switch_off = None self.switch_off = None
self.x_width = 600 self.x_width = 600
self.y_height = 340 self.y_height = 330
self.monitor_center_x = self.winfo_screenwidth() / 2 - (self.x_width / 2) self.monitor_center_x = self.winfo_screenwidth() / 2 - (self.x_width / 2)
self.monitor_center_y = self.winfo_screenheight() / 2 - (self.y_height / 2) self.monitor_center_y = self.winfo_screenheight() / 2 - (self.y_height / 2)
self.resizable(width=False, height=False) self.resizable(width=False, height=False)
@ -156,6 +157,10 @@ class FrameWidgets(ttk.Frame):
try: try:
self.select_tunnel = self.l_box.curselection() self.select_tunnel = self.l_box.curselection()
select_tl = self.l_box.get(self.select_tunnel[0]) select_tl = self.l_box.get(self.select_tunnel[0])
with open('/etc/wire_py/' + select_tl + '.conf', 'r+') as file2:
key = ConToDict.covert_to_dict(file2)
pre_key = key[3]
print(pre_key)
check_call(['nmcli', 'connection', 'delete', select_tl]) check_call(['nmcli', 'connection', 'delete', select_tl])
self.l_box.delete(self.select_tunnel[0]) self.l_box.delete(self.select_tunnel[0])
if Path.is_file(Path('/etc/wire_py/wg_py')): if Path.is_file(Path('/etc/wire_py/wg_py')):
@ -167,11 +172,16 @@ class FrameWidgets(ttk.Frame):
self.wg_autostart.configure(state='disabled') self.wg_autostart.configure(state='disabled')
Path.unlink(path_to_file) Path.unlink(path_to_file)
Path.unlink(Path('/etc/wire_py') / str(select_tl + '.conf')) Path.unlink(Path('/etc/wire_py') / str(select_tl + '.conf'))
with open('/etc/wire_py/.keys', 'r') as readfile:
with open('/etc/wire_py/.keys2', 'w') as writefile:
for line in readfile:
if pre_key not in line.strip("\n"):
writefile.write(line)
os.replace('/etc/wire_py/.keys2', '/etc/wire_py/.keys')
# for disable checkbox when Listbox empty # for disable checkbox when Listbox empty
tl = ListTunnels.tl_list() tl = ListTunnels.tl_list()
if len(tl) == 0: if len(tl) == 0:
self.wg_autostart.configure(state='disabled') self.wg_autostart.configure(state='disabled')
if self.a != '' and self.a == select_tl: if self.a != '' and self.a == select_tl:
self.StrVar.set(value='') self.StrVar.set(value='')
StartStopBTN.button_start(self) StartStopBTN.button_start(self)
@ -180,7 +190,6 @@ class FrameWidgets(ttk.Frame):
self.add.set('') self.add.set('')
self.DNS.set('') self.DNS.set('')
self.enp.set('') self.enp.set('')
return select_tl return select_tl
except IndexError: except IndexError:
pass pass
@ -194,9 +203,9 @@ class FrameWidgets(ttk.Frame):
self.btn_exp.grid(column=0, row=3, padx=15, pady=8) self.btn_exp.grid(column=0, row=3, padx=15, pady=8)
# Label Entry # Label Entry
self.lb_rename = ttk.Entry(self, width=45) self.lb_rename = ttk.Entry(self, width=20)
self.lb_rename.grid(column=2, row=4, padx=30, pady=15, sticky='snw') self.lb_rename.grid(column=2, row=4, padx=30, pady=5, sticky='w')
self.lb_rename.insert(0, 'Max. 12 characters without blanks!') self.lb_rename.insert(0, 'Max. 12 characters!')
self.lb_rename.config(state='disable') self.lb_rename.config(state='disable')
def tl_rename(): def tl_rename():
@ -222,7 +231,7 @@ class FrameWidgets(ttk.Frame):
# Button Rename # Button Rename
self.btn_rename = ttk.Button(self, text='Rename', state='disable', command=tl_rename) self.btn_rename = ttk.Button(self, text='Rename', state='disable', command=tl_rename)
self.btn_rename.grid(column=2, row=4, padx=20, pady=15, sticky='e') self.btn_rename.grid(column=2, row=4, padx=20, pady=10, sticky='e')
# Check Buttons # Check Buttons
self.selected_option = tk.IntVar() self.selected_option = tk.IntVar()
@ -230,7 +239,7 @@ class FrameWidgets(ttk.Frame):
self.autoconnect_var.set(self.auto_con) self.autoconnect_var.set(self.auto_con)
self.autoconnect = tk.Label(self, textvariable=self.autoconnect_var, fg='blue', padx=5) self.autoconnect = tk.Label(self, textvariable=self.autoconnect_var, fg='blue', padx=5)
self.autoconnect.config(font=('Ubuntu', 11)) self.autoconnect.config(font=('Ubuntu', 11))
self.autoconnect.grid(column=0, row=4, sticky='ne', pady=20) self.autoconnect.grid(column=0, row=4, sticky='ne', pady=10)
self.wg_autostart = tk.Checkbutton(self, self.wg_autostart = tk.Checkbutton(self,
text='Autoconnect on:', text='Autoconnect on:',
variable=self.selected_option, variable=self.selected_option,