Wire-Py/wg_func.py

180 lines
6.6 KiB
Python
Raw Normal View History

2024-08-14 22:05:00 +02:00
# Wireguard functions for Wire-Py
import os
import subprocess
from tkinter import filedialog, ttk
import tkinter as tk
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(tk.Tk):
def __init__(self, container, **kwargs):
super().__init__(container, **kwargs)
self.StrVar = None
self.lb_tunnel = None
def green_show_label(self):
self.lb_tunnel = tk.Label(self, textvariable=self.StrVar, fg='green')
self.lb_tunnel.config(font=("Ubuntu", 11, "bold"))
self.lb_tunnel.grid(column=2, padx=10, row=1)
2024-08-21 12:51:07 +02:00
class StartStopBTN(tk.Tk):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.wg_switch = None
self.btn_stst = None
self.wg_vpn_start = tk.PhotoImage(file=r'icons/wg-vpn-start-48.png')
self.wg_vpn_stop = tk.PhotoImage(file=r'icons/wg-vpn-stop-48.png')
def button_stop(self):
self.btn_stst = tk.Button(self, image=self.wg_vpn_stop, bd=0, command=self.wg_switch)
self.btn_stst.grid(column=0, row=1, padx=15, pady=15, sticky="s")
def button_start(self):
self.btn_stst = tk.Button(self, image=self.wg_vpn_start, bd=0, command=self.wg_switch)
self.btn_stst.grid(column=0, row=1, padx=15, pady=15, sticky="s")
class ConToDict:
@classmethod
def covert_to_dict(cls, file):
dictlist = []
for lines in file.readlines():
lineplit = lines.split()
dictlist = dictlist + lineplit
dictlist.remove('[Interface]')
dictlist.remove('[Peer]')
for items in dictlist:
if items == '=':
dictlist.remove(items)
for i in dictlist:
a = [dictlist[0], dictlist[1]]
b = [dictlist[2], dictlist[3]]
c = [dictlist[4], dictlist[5]]
d = [dictlist[6], dictlist[7]]
e = [dictlist[8], dictlist[9]]
f = [dictlist[10], dictlist[11]]
g = [dictlist[12], dictlist[13]]
h = [dictlist[14], dictlist[15]]
newlist = [a, b, c, d, e, f, g, h]
finaldict = {}
for elements in newlist:
finaldict[elements[0]] = elements[1]
address = finaldict['Address']
dns = finaldict['DNS']
endpoint = finaldict['Endpoint']
with open('dict_to_address', 'w+') as data:
data.write(address + '\n')
data.write(dns + '\n')
data.write(endpoint + '\n')
data.close()
class TunnelActiv:
@staticmethod
def active(): # Shows the active tunnel
active = os.popen('nmcli con show --active | grep -iPo "(.*)(wireguard)"').read().split()
if not active:
active = ''
else:
active = active[0]
return active
class ListTunnels:
@staticmethod
def tl_list():
wg_s = os.popen('nmcli con show | grep -iPo "(.*)(wireguard)"').read().split()
tl = wg_s[::3] # tl = Tunnel list # Show of 4.Element in list
return tl
class ImportTunnel:
def __init__(self):
self.select_tunnel = None
self.wg_switch = None
self.btn_stst = None
self.lb_tunnel = None
self.StrVar = None
self.a = None
self.l_box = None
def wg_import_select(self):
try:
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()
pathsplit = filepath.split("/")
pathsplit1 = pathsplit[-1]
if "PrivateKey = " in read and "PublicKey = " in read:
if len(pathsplit1) > 17:
pathsplit = pathsplit1[len(pathsplit1) - 17:]
os.rename(filepath, os.environ['HOME'] + '/tester/' + str(pathsplit))
os.system('nmcli connection down ' + str(TunnelActiv.active()))
os.system('nmcli connection import type wireguard file ' + os.environ['HOME'] + '/tester/' +
str(pathsplit))
os.system('nmcli con mod ' + str(pathsplit[:-5]) + ' connection.autoconnect no')
else:
subprocess.call('cp ' + str(filepath) + ' ' + os.environ['HOME'] + '/tester/', shell=True)
os.system('nmcli connection down ' + str(TunnelActiv.active()))
os.system('nmcli connection import type wireguard file ' + str(filepath))
os.system('nmcli con mod ' + str(pathsplit1[:-5]) + ' connection.autoconnect no')
self.StrVar.set(value=' ')
self.a = TunnelActiv.active()
self.l_box.insert(0, self.a)
self.l_box.update()
self.StrVar = tk.StringVar()
self.StrVar.set(self.a)
GreenLabel.green_show_label(self)
2024-08-21 12:51:07 +02:00
StartStopBTN.button_stop(self)
wg_read = os.environ['HOME'] + '/tester/' + str(self.a) + '.conf'
file = open(wg_read, 'r')
ConToDict.covert_to_dict(file)
file.close()
if "PrivateKey = " not in read:
Message()
except EOFError:
pass
except TypeError:
pass
except FileNotFoundError:
pass
2024-08-14 22:05:00 +02:00
class ExportTunnels:
@staticmethod
def wg_export():
try:
wg_exp = os.popen('nmcli con show | grep -iPo "(.*)(wireguard)"').read().split()
wg_exp = wg_exp[1]
return wg_exp
except IndexError:
pass