Compare commits

..

No commits in common. "main" and "wire-py-reformat-14-08-2024" have entirely different histories.

8 changed files with 143 additions and 258 deletions

View File

@ -4,16 +4,10 @@
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="940e1630-c825-4d4c-be80-bc11f543c122" name="Changes" comment="little fixes a labels when stop and start, installer first functions works">
<change afterPath="$PROJECT_DIR$/message.py" afterDir="false" />
<change afterPath="$PROJECT_DIR$/test.py" afterDir="false" />
<change afterPath="$PROJECT_DIR$/test2.py" afterDir="false" />
<list default="true" id="940e1630-c825-4d4c-be80-bc11f543c122" name="Changes" comment="add Options in">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/install.py" beforeDir="false" afterPath="$PROJECT_DIR$/install.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/main.py" beforeDir="false" afterPath="$PROJECT_DIR$/main.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/start_wg.py" beforeDir="false" afterPath="$PROJECT_DIR$/start_wg.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_py" beforeDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
@ -50,19 +44,14 @@
<component name="PropertiesComponent">{
&quot;keyToString&quot;: {
&quot;ASKED_ADD_EXTERNAL_FILES&quot;: &quot;true&quot;,
&quot;Python.INSTALL.executor&quot;: &quot;Run&quot;,
&quot;Python.install.executor&quot;: &quot;Run&quot;,
&quot;Python.main.executor&quot;: &quot;Run&quot;,
&quot;Python.messagebox.executor&quot;: &quot;Run&quot;,
&quot;Python.start_wg.executor&quot;: &quot;Run&quot;,
&quot;Python.wg_func.executor&quot;: &quot;Run&quot;,
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
&quot;git-widget-placeholder&quot;: &quot;main&quot;,
&quot;last_opened_file_path&quot;: &quot;/home/punix/Pyapps/wire-py&quot;,
&quot;settings.editor.selected.configurable&quot;: &quot;preferences.lookFeel&quot;
}
}</component>
<component name="RunManager" selected="Python.main">
<component name="RunManager">
<configuration name="main" type="PythonConfigurationType" factoryName="Python" nameIsGenerated="true">
<module name="wire-py" />
<option name="ENV_FILES" value="" />
@ -85,33 +74,6 @@
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
<configuration name="start_wg" type="PythonConfigurationType" factoryName="Python" temporary="true" nameIsGenerated="true">
<module name="wire-py" />
<option name="ENV_FILES" value="" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/start_wg.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="false" />
<option name="REDIRECT_INPUT" value="false" />
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
<recent_temporary>
<list>
<item itemvalue="Python.start_wg" />
</list>
</recent_temporary>
</component>
<component name="SharedIndexes">
<attachedChunks>
@ -329,47 +291,10 @@
<option name="project" value="LOCAL" />
<updated>1725567453540</updated>
</task>
<task id="LOCAL-00026" summary="little fixes">
<option name="closed" value="true" />
<created>1725639633873</created>
<option name="number" value="00026" />
<option name="presentableId" value="LOCAL-00026" />
<option name="project" value="LOCAL" />
<updated>1725639633873</updated>
</task>
<task id="LOCAL-00027" summary="little fixes">
<option name="closed" value="true" />
<created>1725746027132</created>
<option name="number" value="00027" />
<option name="presentableId" value="LOCAL-00027" />
<option name="project" value="LOCAL" />
<updated>1725746027132</updated>
</task>
<task id="LOCAL-00028" summary="little fixes replace os.system with check_call&#10;first steps in install Script add wg_start.service file">
<option name="closed" value="true" />
<created>1725820337669</created>
<option name="number" value="00028" />
<option name="presentableId" value="LOCAL-00028" />
<option name="project" value="LOCAL" />
<updated>1725820337669</updated>
</task>
<task id="LOCAL-00029" summary="little fixes a labels when stop and start, installer first functions works">
<option name="closed" value="true" />
<created>1725991610908</created>
<option name="number" value="00029" />
<option name="presentableId" value="LOCAL-00029" />
<option name="project" value="LOCAL" />
<updated>1725991610908</updated>
</task>
<option name="localTasksCounter" value="30" />
<option name="localTasksCounter" value="26" />
<servers />
</component>
<component name="Vcs.Log.Tabs.Properties">
<option name="OPEN_GENERIC_TABS">
<map>
<entry key="f9756e7d-0c5c-4b84-84e4-660314c46ea4" value="TOOL_WINDOW" />
</map>
</option>
<option name="TAB_STATES">
<map>
<entry key="MAIN">
@ -389,16 +314,13 @@
</State>
</value>
</entry>
<entry key="f9756e7d-0c5c-4b84-84e4-660314c46ea4">
<value>
<State />
</value>
</entry>
</map>
</option>
</component>
<component name="VcsManagerConfiguration">
<option name="ADD_EXTERNAL_FILES_SILENTLY" value="true" />
<MESSAGE value="Tunnel Start and Stop Work" />
<MESSAGE value="wg_import_select in wg_func.py extended" />
<MESSAGE value="add class Frame and class Massage, delete funktion go 100%, add resize window" />
<MESSAGE value="add class Frame and class Massage, delete funktion go 100%, add resize window, add warning pic" />
<MESSAGE value="add class ListTunnels and class ImportTunnel, and add class ExportTunnels (ExportTunnels no finish)" />
@ -421,9 +343,6 @@
<MESSAGE value="add if question and add autoconnect, autoconnect_var to class Filehandle in box_set no finish!" />
<MESSAGE value="fixes on empty Listbox now is disable and now works autoconnect label with read and write, delete works now with read and write" />
<MESSAGE value="add Frame widget 3&#10;for Buttons and Listbox with Scrollbar.&#10;all Widgets new format&#10;delete works now of disable checkbox when Listbox empty (part two)" />
<MESSAGE value="little fixes" />
<MESSAGE value="little fixes replace os.system with check_call&#10;first steps in install Script add wg_start.service file" />
<MESSAGE value="little fixes a labels when stop and start, installer first functions works" />
<option name="LAST_COMMIT_MESSAGE" value="little fixes a labels when stop and start, installer first functions works" />
<option name="LAST_COMMIT_MESSAGE" value="add Frame widget 3&#10;for Buttons and Listbox with Scrollbar.&#10;all Widgets new format&#10;delete works now of disable checkbox when Listbox empty (part two)" />
</component>
</project>

View File

@ -1,34 +0,0 @@
#!/usr/bin/python3
from pathlib import Path
from getpass import getpass
# for services file in /lib/systemd/system/
config_path = Path.home() / ".config" / "wire_py" / "wg_py"
start_file = f'''\
#!/usr/bin/python3
from subprocess import check_call
path_to_file = {str(config_path)!r}
with open(path_to_file, 'r') as file:
*_, line = file
a_con = line[5:]
check_call(['nmcli', 'connection', 'up', a_con])
'''
Path("start_wg.py").write_text(start_file)
config_path.parent.mkdir(exist_ok=True)
if not Path.exists(config_path):
config_path.write_text("false")
# Prompt the user for the sudo password
#sudo_password = getpass('Enter sudo password: ')
#def cp_files():
# Define the command to run the Python script with sudo
#command = ['sudo', '-S', 'python3', 'script.py']
# Run the command as a subprocess, passing the sudo password
#subprocess.run(command, input=sudo_password.encode(), check=True)

60
main.py
View File

@ -1,13 +1,13 @@
#!/usr/bin/python3
import os
import tkinter as tk
from subprocess import check_call
from tkinter import ttk
from pathlib import Path
from wg_func import (TunnelActiv, ListTunnels, ImportTunnel, ConToDict, GreenLabel, StartStopBTN, ShowAddress,
FileHandle, ExportTunnels, OnOff)
font_color = '#4011a7'
replacement = ''
class MainWindow(tk.Tk):
@ -35,7 +35,8 @@ class MainWindow(tk.Tk):
# App Menu
self.app_menu = tk.Menu(self, borderwidth=0)
for item in self.app_menu.keys():
print(item, ': ', self.app_menu[item])
self.configure(menu=self.app_menu)
self.app_menu.add_cascade(label='?')
@ -105,6 +106,7 @@ class FrameWidgets(ttk.Frame):
# Listbox with Scrollbar
def enable_check_box(event):
tl = ListTunnels.tl_list()
print(len(tl))
if len(tl) != 0:
self.wg_autostart.configure(state='normal')
@ -127,12 +129,13 @@ class FrameWidgets(ttk.Frame):
# Button Vpn
if self.a != '':
StartStopBTN.button_stop(self)
wg_read = Path.home() / 'tester/' / str(self.a + '.conf')
with open(wg_read, 'r') as file:
wg_read = os.environ['HOME'] + '/tester/' + str(self.a) + '.conf'
file = open(wg_read, 'r')
data = ConToDict.covert_to_dict(file)
# Address Label
ShowAddress.init_and_report(self, data)
ShowAddress.show_data(self)
file.close()
else:
StartStopBTN.button_start(self)
# Address Label
@ -151,32 +154,38 @@ class FrameWidgets(ttk.Frame):
try:
self.select_tunnel = self.l_box.curselection()
select_tl = self.l_box.get(self.select_tunnel[0])
check_call(['nmcli', 'connection', 'delete', select_tl])
os.system('nmcli connection delete ' + str(select_tl))
self.l_box.delete(self.select_tunnel[0])
os.remove(Path.home() / 'tester/' / str(select_tl + '.conf'))
os.remove(os.environ['HOME'] + '/tester/' + str(select_tl) + '.conf')
path_to_file = Path.home() / '.config/wire_py/wg_py'
with open(path_to_file, 'r') as file2:
for line in file2.readlines():
a_con = line[5:]
if select_tl == a_con:
self.selected_option.set(0)
self.autoconnect_var.set('no Autoconnect')
del_tl_read = open('wg_py.xml', 'r')
if 'false ' in del_tl_read:
first_word = 'false '
else:
first_word = 'true '
word_replace = ''
# using the for loop
for line in del_tl_read:
line = line.strip()
changes = line.replace(first_word + select_tl, '')
word_replace = word_replace + changes + "\n"
del_tl_read.close()
del_tl = open('wg_py.xml', 'w')
del_tl.write(word_replace)
del_tl.close()
# for disable checkbox when Listbox empty
tl = ListTunnels.tl_list()
if len(tl) == 0:
self.wg_autostart.configure(state='disabled')
with open(path_to_file, 'w') as file2:
file2.write('false')
if self.a != '' and self.a == select_tl:
self.StrVar.set(value='')
StartStopBTN.button_start(self)
self.l_box.update()
# Address Label
self.add.set('')
self.DNS.set('')
self.enp.set('')
ShowAddress.label_empty(self)
return select_tl
except IndexError:
@ -220,13 +229,14 @@ class FrameWidgets(ttk.Frame):
StartStopBTN.button_start(self)
self.select_tunnel = self.l_box.curselection()
select_tl = self.l_box.get(self.select_tunnel[0])
check_call(['nmcli', 'connection', 'up', select_tl])
wg_read = Path.home() / 'tester/' / str(select_tl + '.conf')
with open(wg_read, 'r') as file:
os.system('nmcli connection up ' + str(select_tl))
wg_read = os.environ['HOME'] + '/tester/' + str(select_tl) + '.conf'
file = open(wg_read, 'r')
data = ConToDict.covert_to_dict(file)
# Address Label
ShowAddress.init_and_report(self, data)
ShowAddress.show_data(self)
file.close()
# Button Start/Stop
StartStopBTN.button_stop(self)
self.a = TunnelActiv.active()
@ -236,16 +246,14 @@ class FrameWidgets(ttk.Frame):
elif self.a != '':
# Button Start/Stop
StartStopBTN.button_stop(self)
check_call(['nmcli', 'connection', 'down', self.a])
os.system('nmcli connection down ' + str(self.a))
# Button Start/Stop
StartStopBTN.button_start(self)
self.a = TunnelActiv.active()
self.StrVar.set('')
GreenLabel.green_show_label(self)
# Address Label
self.add.set('')
self.DNS.set('')
self.enp.set('')
ShowAddress.label_empty(self)
ShowAddress.show_data(self)
except IndexError:
pass

View File

@ -1,9 +0,0 @@
#!/usr/bin/python3
from subprocess import check_call
path_to_file = '/home/punix/.config/wire_py/wg_py'
with open(path_to_file, 'r') as file:
*_, line = file
a_con = line[5:]
check_call(['nmcli', 'connection', 'up', a_con])

View File

@ -4,40 +4,37 @@ import shutil
from datetime import datetime
from tkinter import filedialog, ttk
import tkinter as tk
from pathlib import Path
from subprocess import check_call
font_color = '#4011a7'
path_to_file = Path.home() / '.config/wire_py/wg_py'
def msg_window():
msg = tk.Toplevel()
msg.resizable(width=False, height=False)
msg.x_width = 340
msg.y_height = 140
msg.title('Import error!')
msg.monitor_center_x = msg.winfo_screenwidth() / 2 - (msg.x_width / 2)
msg.monitor_center_y = msg.winfo_screenheight() / 2 - (msg.y_height / 2)
msg.geometry('%dx%d+%d+%d' % (msg.x_width, msg.y_height, msg.monitor_center_x, msg.monitor_center_y))
msg.columnconfigure(0, weight=1)
msg.configure(pady=20)
msg.warning = tk.PhotoImage(file=r'icons/warning_64.png')
msg.i_warning = tk.Label(msg, image=msg.warning)
msg.i_warning.grid(column=0, row=0)
label = tk.Label(msg, text='Oh... no valid Wireguard File!\nPlease select a valid Wireguard File')
label.config(font=('Ubuntu', 11), padx=15, pady=15)
label.grid(column=1, row=0)
button = tk.Button(msg, text='OK', command=msg.destroy)
button.config(padx=15, pady=5)
button.grid(column=0, columnspan=2, row=1)
wg_icon_2 = tk.PhotoImage(file=r'icons/wg-stop.png')
msg.iconphoto(True, wg_icon_2)
msg.winfo_toplevel()
class Message(tk.Tk):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.warning_pic = None
self.x_width = 300
self.y_height = 120
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.resizable(width=False, height=False)
self.title('Import error!')
self.configure()
self.geometry('%dx%d+%d+%d' % (self.x_width, self.y_height, self.monitor_center_x, self.monitor_center_y))
self.columnconfigure(0, weight=1)
self.label = tk.Label(self, image=self.warning_pic,
text='Oh... no valid Wireguard File!\nPlease select a valid Wireguard File')
self.label.config(font=('Ubuntu', 11), padx=15, pady=15)
self.label.grid(column=0, row=0)
self.button = tk.Button(self, text='OK', command=self.destroy)
self.button.config(padx=15, pady=5)
self.button.grid(column=0, row=1)
class GreenLabel:
def __init__(self):
class GreenLabel(tk.Tk):
def __init__(self, container, **kwargs):
super().__init__(container, **kwargs)
self.StrVar = None
self.lb_tunnel = None
@ -48,15 +45,10 @@ class GreenLabel:
self.columnconfigure(2, weight=1)
self.rowconfigure(0, weight=1)
def columnconfigure(self, param, weight):
pass
def rowconfigure(self, param, weight):
pass
class StartStopBTN:
def __init__(self):
class StartStopBTN(tk.Tk):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.lb_frame_btn_lbox = None
self.wg_switch = None
self.btn_stst = None
@ -119,8 +111,9 @@ class TunnelActiv:
return active
class ShowAddress:
def __init__(self):
class ShowAddress(tk.Tk):
def __init__(self, container, **kwargs):
super().__init__(container, **kwargs)
self.lb_frame2 = None
self.lb_frame = None
self.endpoint = None
@ -168,9 +161,10 @@ class ListTunnels:
class ImportTunnel:
def __init__(self):
self.enp = None
self.DNS = None
self.add = None
self.select_tunnel = None
self.wg_switch = None
self.btn_stst = None
@ -181,30 +175,27 @@ class ImportTunnel:
def wg_import_select(self):
try:
filepath = filedialog.askopenfilename(initialdir=Path.home(), title='Select Wireguard config File',
filetypes=[('WG config files', '*.conf')], )
with open(filepath, 'r') as file:
filepath = filedialog.askopenfilename(initialdir=os.environ['HOME'], title='Select Wireguard config File',
filetypes=[('WG config files', '*.conf')])
file = open(filepath, 'r')
read = file.read()
file.close()
path_split = filepath.split('/')
path_split1 = path_split[-1]
self.a = TunnelActiv.active()
if 'PrivateKey = ' in read and 'PublicKey = ' in read:
if len(path_split1) > 17:
p1 = shutil.copy(filepath, Path.home() / 'tester/')
p1 = shutil.copy(filepath, os.environ['HOME'] + '/tester/')
path_split = path_split1[len(path_split1) - 17:]
os.rename(p1, Path.home() / 'tester/' / str(path_split))
os.rename(p1, os.environ['HOME'] + '/tester/' + str(path_split))
if self.a != '':
check_call(['nmcli', 'connection', 'down', TunnelActiv.active()])
ShowAddress.label_empty(self)
check_call(['nmcli', 'connection', 'import', 'type', 'wireguard', 'file', Path.home() / 'tester' /
path_split])
os.system('nmcli connection down ' + str(TunnelActiv.active()))
os.system('nmcli connection import type wireguard file ' + os.environ['HOME'] + '/tester/' +
str(path_split))
else:
shutil.copy(filepath, Path.home() / 'tester/')
shutil.copy(filepath, os.environ['HOME'] + '/tester/')
if self.a != '':
check_call(['nmcli', 'connection', 'down', TunnelActiv.active()])
ShowAddress.label_empty(self)
check_call(['nmcli', 'connection', 'import', 'type', 'wireguard', 'file', filepath])
os.system('nmcli connection down ' + str(TunnelActiv.active()))
os.system('nmcli connection import type wireguard file ' + str(filepath))
self.StrVar.set('')
self.a = TunnelActiv.active()
@ -214,15 +205,19 @@ class ImportTunnel:
self.StrVar.set(self.a)
GreenLabel.green_show_label(self)
StartStopBTN.button_stop(self)
wg_read = Path.home() / 'tester/' / str(self.a + '.conf')
with open(wg_read, 'r') as file:
wg_read = os.environ['HOME'] + '/tester/' + str(self.a) + '.conf'
file = open(wg_read, 'r')
data = ConToDict.covert_to_dict(file)
# Address Label
ShowAddress.init_and_report(self, data)
ShowAddress.show_data(self)
check_call(['nmcli', 'con', 'mod', self.a, 'connection.autoconnect', 'no'])
file.close()
os.system('nmcli con mod ' + str(self.a) + ' connection.autoconnect no')
new_tl = open('wg_py.xml', 'a')
new_tl.write('false ' + str(self.a) + '\n')
new_tl.close()
if 'PrivateKey = ' not in read:
msg_window()
Message()
except EOFError:
pass
except TypeError:
@ -242,20 +237,34 @@ class FileHandle:
self.tl = None
self.selected_option = None
self.l_box = None
self.select_tunnel = None
def box_set(self):
word_replace = ''
try:
select_tunnel = self.l_box.curselection()
select_tl = self.l_box.get(select_tunnel[0])
self.select_tunnel = self.l_box.curselection()
select_tl = self.l_box.get(self.select_tunnel[0])
if self.selected_option.get() == 0:
with open(path_to_file, 'w') as off:
off.write('false ' + '\n')
tl = ListTunnels.tl_list()
if len(tl) == 0:
self.wg_autostart.configure(state='disabled')
set_on = open('wg_py.xml', 'r')
# using the for loop
for line in set_on:
line = line.strip()
changes = line.replace('true ' + select_tl, 'false ' + select_tl)
os.system('nmcli con mod ' + str(self.auto_con) + ' connection.autoconnect no')
word_replace = word_replace + changes + "\n"
set_on.close()
if self.selected_option.get() >= 1:
with open(path_to_file, 'w') as set_on:
set_on.write('true ' + select_tl)
set_on = open('wg_py.xml', 'r')
# using the for loop
for line in set_on:
line = line.strip()
changes = line.replace('false ' + select_tl, 'true ' + select_tl)
os.system('nmcli con mod ' + str(select_tl) + ' connection.autoconnect yes')
word_replace = word_replace + changes + "\n"
set_on.close()
set_off = open('wg_py.xml', 'w')
set_off.write(word_replace)
set_off.close()
except IndexError:
self.selected_option.set(1)
@ -263,26 +272,26 @@ class FileHandle:
OnOff.on_off(self)
class OnOff:
def __init__(self):
self.wg_autostart = None
self.selected_option = None
self.auto_con = None
self.autoconnect = None
self.autoconnect_var = None
class OnOff(tk.Tk, FileHandle):
def __init__(self, container, **kwargs):
super().__init__(container, **kwargs)
self.lb_frame_buttons = None
def on_off(self):
with open(path_to_file, 'r') as file:
for line in file.readlines():
a_connect = line
a_connect = {}
on_or_off = open('wg_py.xml', 'r')
for line in on_or_off.readlines():
line_splitted = line.split()
a_connect[line_splitted[0]] = line_splitted[1]
if 'true' in a_connect:
self.selected_option.set(1)
self.autoconnect_var.set('')
self.auto_con = a_connect[5:]
self.auto_con = a_connect['true']
else:
self.wg_autostart.configure(state='disabled')
self.auto_con = 'no Autoconnect'
on_or_off.close()
self.autoconnect_var = tk.StringVar()
self.autoconnect_var.set(self.auto_con)
@ -295,12 +304,12 @@ class ExportTunnels:
@staticmethod
def wg_export():
now_time = datetime.now()
now_datetime = now_time.strftime('wg-exp-' + '%m-%d-%Y' + '-' + '%H:%M')
now_datetime = now_time.strftime('/wg-exp-' + '%m-%d-%Y' + '-' + '%H:%M')
tl = ListTunnels.tl_list()
try:
if len(tl) != 0:
wg_tar = Path.home() / now_datetime
p_to_conf = Path.home() / 'tester/'
wg_tar = os.environ['HOME'] + now_datetime
p_to_conf = os.environ['HOME'] + '/tester'
shutil.make_archive(wg_tar, 'zip', p_to_conf)
#if zip_full != 0:
#print('Export erfolgraeich')

0
wg_py
View File

2
wg_py.xml Normal file
View File

@ -0,0 +1,2 @@
false peer_iasus
false rverEppingen

View File

@ -1,10 +0,0 @@
[Unit]
Description=Automatic Tunnel Start
After=network-online.target
[Service]
Type=oneshot
ExecStartPre=/bin/sleep 3
ExecStart=/bin/start_wg.py
[Install]
WantedBy=multi-user.target