From 89c1bb6469b80920903e28dbf665fe6cf3c1a8c9 Mon Sep 17 00:00:00 2001 From: Benjamin W Crouch II Date: Sun, 12 Jan 2020 21:40:18 -0600 Subject: [PATCH 01/24] Added configur option to active interfaces. Associated the configure click to open a new configuration window, which will be specific to the interface. In the process of building out the Configuration menue. --- src/trayicon.py | 14 +++++++++++++- todo.txt | 22 ++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 todo.txt diff --git a/src/trayicon.py b/src/trayicon.py index 2a6c826..cad6314 100755 --- a/src/trayicon.py +++ b/src/trayicon.py @@ -64,10 +64,13 @@ def nm_menu(self): wired_item = Gtk.MenuItem("Wired %s Connected" % cardnum) wired_item.set_sensitive(False) self.menu.append(wired_item) - disconnect_item = Gtk.ImageMenuItem("Disable") + disconnect_item = Gtk.ImageMenuItem(f"Disable {netcard}") disconnect_item.connect("activate", self.disconnectcard, netcard) self.menu.append(disconnect_item) + configure_item = Gtk.ImageMenuItem(f"Configure {netcard}") + configure_item.connect("activate", self.configuration_window, netcard) + self.menu.append(configure_item) elif connection_state == "Disconnected": notonline = Gtk.MenuItem("Wired %s Disconnected" % cardnum) notonline.set_sensitive(False) @@ -118,6 +121,9 @@ def nm_menu(self): diswifi = Gtk.MenuItem("Disable Wifi %s" % wifinum) diswifi.connect("activate", self.disable_Wifi, netcard) self.menu.append(diswifi) + configure_item = Gtk.ImageMenuItem(f"Configure {netcard}") + configure_item.connect("activate", self.configuration_window, netcard) + self.menu.append(configure_item) self.menu.append(Gtk.SeparatorMenuItem()) wifinum += 1 @@ -173,6 +179,12 @@ def wifiListMenu(self, wificard, cbssid, passes, cards): wiconncmenu.append(menu_item) self.menu.append(avconnmenu) + def configuration_window(self, widget, interface): + iConfWindow = Gtk.Window() + iConfWindow.set_title(f"Configuration Menu for Interface {interface}") + iConfWindow.set_default_size(600,400) + iConfWindow.show() + def menu_click_open(self, widget, ssid, bssid, wificard): if bssid in open(wpa_supplican).read(): connectToSsid(ssid, wificard) diff --git a/todo.txt b/todo.txt new file mode 100644 index 0000000..05b6971 --- /dev/null +++ b/todo.txt @@ -0,0 +1,22 @@ +XXX1) Add configure button for every detected interface + +XXX2) When you click configure, it needs to open a window + +3) Window should have radio button for DHCP or static. +3b) If DHCP is enabled, make it so you can't add static IP information into the form. + +4) Need to have an OK button for the window + +5) Neet to have a cancle button for the window. + +6) When the person clicks cancle, it should refresh the window with the unchanged settings + +7) When somebody clicks the OK button, input validation and system configuration checking need to happen. + +8) If everything checks out, then apply changes to system. + +9) Confirm that expected changes to the system were correct and successful. + +10) Once settings have been set successfully, add confirmation to the window. + +11) Make the user close the window using system window buttons. Such as yellow, green, red buttons in Mate. \ No newline at end of file From 1e9648b4f658d23d6734fc20635f1a08b6467114 Mon Sep 17 00:00:00 2001 From: Benjamin W Crouch II Date: Mon, 13 Jan 2020 11:15:05 -0600 Subject: [PATCH 02/24] Moved Todo to projects. --- todo.txt | 22 ---------------------- 1 file changed, 22 deletions(-) delete mode 100644 todo.txt diff --git a/todo.txt b/todo.txt deleted file mode 100644 index 05b6971..0000000 --- a/todo.txt +++ /dev/null @@ -1,22 +0,0 @@ -XXX1) Add configure button for every detected interface - -XXX2) When you click configure, it needs to open a window - -3) Window should have radio button for DHCP or static. -3b) If DHCP is enabled, make it so you can't add static IP information into the form. - -4) Need to have an OK button for the window - -5) Neet to have a cancle button for the window. - -6) When the person clicks cancle, it should refresh the window with the unchanged settings - -7) When somebody clicks the OK button, input validation and system configuration checking need to happen. - -8) If everything checks out, then apply changes to system. - -9) Confirm that expected changes to the system were correct and successful. - -10) Once settings have been set successfully, add confirmation to the window. - -11) Make the user close the window using system window buttons. Such as yellow, green, red buttons in Mate. \ No newline at end of file From ddcc15226406f330e8d2cabbc74554a268528445 Mon Sep 17 00:00:00 2001 From: Benjamin W Crouch II Date: Fri, 17 Jan 2020 10:55:25 -0600 Subject: [PATCH 03/24] Modified calls from trayicon.py to netcardmgr. Updated netcardmgr to add flags to explicitly call certain classes. Fleshed out the configuration window and put in some dummy information as placeholders on the tabs. --- src/netcardmgr | 55 ++++++++++++++++++++++++++++++++++++++++++++++++- src/trayicon.py | 13 +++++------- 2 files changed, 59 insertions(+), 9 deletions(-) diff --git a/src/netcardmgr b/src/netcardmgr index fe40ecc..e88f14e 100755 --- a/src/netcardmgr +++ b/src/netcardmgr @@ -29,9 +29,13 @@ # # $Id: netcardmgr.py v 0.1 Saturday, February 08 2014 Eric Turgeon $ +import gi +gi.require_version('Gtk', '3.0') +from gi.repository import Gtk, GObject, GLib from subprocess import Popen, PIPE import os import re +import sys from time import sleep ncard = 'ifconfig -l' @@ -120,5 +124,54 @@ class autoConfigure(): sleep(1) wlanNum += 1 +class netCardConfigWindow(Gtk.Window): -autoConfigure() + def __init__(self): + # Build Default Window + Gtk.Window.__init__(self, title="Network Interface Configuration") + self.set_default_size(600,400) + + # Build Tab 1 Content + testbutton = Gtk.Button(label="IPv4 Stuff") + testbutton.connect("clicked", self.on_button_clicked) + + # Build Tab 2 Content + testbutton2 = Gtk.Button(label="IPv6 Stuff") + testbutton2.connect("clicked", self.on_button_clicked) + + # Build Tab 3 Content + testbutton3 = Gtk.Button(label="VPN Stuff") + testbutton3.connect("clicked", self.on_button_clicked) + + # Build Notebook + nb = Gtk.Notebook() + nb.set_tab_pos(2) + self.add(nb) + + # Apply Tab 1 content and formatting + nb.append_page(testbutton) + nb.set_tab_label_text(testbutton, "IPv4 Settings") + + # Apply Tab 2 content and formatting + nb.append_page(testbutton2) + nb.set_tab_label_text(testbutton2, "IPv6 Settings") + + # Apply Tab 3 content and formatting + nb.append_page(testbutton3) + nb.set_tab_label_text(testbutton3, "VPN") + + def on_button_clicked(self, widget): + print(f"Hello World") + +def openNetCardConfigwindow(): + win = netCardConfigWindow() + win.connect("destroy", Gtk.main_quit) + win.show_all() + Gtk.main() + +if "-auto" in sys.argv: + autoConfigure() +elif "-configure" in sys.argv: + openNetCardConfigwindow() +else: + print(f"No acceptable flags were passed to the function.") \ No newline at end of file diff --git a/src/trayicon.py b/src/trayicon.py index cad6314..758ff52 100755 --- a/src/trayicon.py +++ b/src/trayicon.py @@ -69,7 +69,7 @@ def nm_menu(self): netcard) self.menu.append(disconnect_item) configure_item = Gtk.ImageMenuItem(f"Configure {netcard}") - configure_item.connect("activate", self.configuration_window, netcard) + configure_item.connect("activate", self.configuration_window_open, netcard) self.menu.append(configure_item) elif connection_state == "Disconnected": notonline = Gtk.MenuItem("Wired %s Disconnected" % cardnum) @@ -122,7 +122,7 @@ def nm_menu(self): diswifi.connect("activate", self.disable_Wifi, netcard) self.menu.append(diswifi) configure_item = Gtk.ImageMenuItem(f"Configure {netcard}") - configure_item.connect("activate", self.configuration_window, netcard) + configure_item.connect("activate", self.configuration_window_open, netcard) self.menu.append(configure_item) self.menu.append(Gtk.SeparatorMenuItem()) wifinum += 1 @@ -179,11 +179,8 @@ def wifiListMenu(self, wificard, cbssid, passes, cards): wiconncmenu.append(menu_item) self.menu.append(avconnmenu) - def configuration_window(self, widget, interface): - iConfWindow = Gtk.Window() - iConfWindow.set_title(f"Configuration Menu for Interface {interface}") - iConfWindow.set_default_size(600,400) - iConfWindow.show() + def configuration_window_open(self, widget, interface): + os.system( "doas netcardmgr -configure" ) def menu_click_open(self, widget, ssid, bssid, wificard): if bssid in open(wpa_supplican).read(): @@ -305,7 +302,7 @@ def default_wifi_state(self, defaultdev): def checkfornewcard(self): if os.path.exists("/usr/local/bin/netcardmgr"): if isanewnetworkcardinstall() is True: - os.system("doas netcardmgr") + os.system("doas netcardmgr -auto") def updatetrayicon(self, defaultdev, card_type): if card_type is None: From 7e5e1ba86359acceef44ccbf75bc0b28e55b809e Mon Sep 17 00:00:00 2001 From: Benjamin W Crouch II Date: Sat, 18 Jan 2020 18:42:16 -0600 Subject: [PATCH 04/24] Just experimenting with some GTK formatting. --- src/netcardmgr | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/src/netcardmgr b/src/netcardmgr index e88f14e..3cda395 100755 --- a/src/netcardmgr +++ b/src/netcardmgr @@ -132,9 +132,30 @@ class netCardConfigWindow(Gtk.Window): self.set_default_size(600,400) # Build Tab 1 Content + testbutton = Gtk.Button(label="IPv4 Stuff") testbutton.connect("clicked", self.on_button_clicked) + labelOne = Gtk.Label("Interface:") + labelTwo = Gtk.Label("Interface:2") + labelThree = Gtk.Label("Interface:3") + + interfaceBox = Gtk.Box(0, 10) + interfaceBox.pack_start(labelOne, False, False, 0) + interfaceBox.pack_end(testbutton, True, True, 0) + + boxTwo = Gtk.Box(0, 10) + boxTwo.pack_start(labelTwo, True, True, 0) + boxTwo.pack_end(labelThree, True, True, 0) + + gridOne = Gtk.Grid() + gridOne.set_column_homogeneous(True) + gridOne.set_row_homogeneous(False) + gridOne.set_column_spacing(5) + gridOne.set_row_spacing(10) + gridOne.attach(interfaceBox, 0, 0, 4, 1) + gridOne.attach(boxTwo, 0, 1, 4, 1) + # Build Tab 2 Content testbutton2 = Gtk.Button(label="IPv6 Stuff") testbutton2.connect("clicked", self.on_button_clicked) @@ -149,8 +170,8 @@ class netCardConfigWindow(Gtk.Window): self.add(nb) # Apply Tab 1 content and formatting - nb.append_page(testbutton) - nb.set_tab_label_text(testbutton, "IPv4 Settings") + nb.append_page(gridOne) + nb.set_tab_label_text(gridOne, "IPv4 Settings") # Apply Tab 2 content and formatting nb.append_page(testbutton2) From a82417487753d0bd7874699cd8587b56371d3736 Mon Sep 17 00:00:00 2001 From: Benjamin W Crouch II Date: Sun, 19 Jan 2020 13:32:57 -0600 Subject: [PATCH 05/24] Fixed my interface selection issue. --- src/netcardmgr | 41 ++++++++++++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/src/netcardmgr b/src/netcardmgr index 3cda395..3ae11d5 100755 --- a/src/netcardmgr +++ b/src/netcardmgr @@ -129,22 +129,45 @@ class netCardConfigWindow(Gtk.Window): def __init__(self): # Build Default Window Gtk.Window.__init__(self, title="Network Interface Configuration") - self.set_default_size(600,400) + self.set_default_size(475,450) # Build Tab 1 Content - testbutton = Gtk.Button(label="IPv4 Stuff") - testbutton.connect("clicked", self.on_button_clicked) + # Interface Drop Down Combo Box - labelOne = Gtk.Label("Interface:") - labelTwo = Gtk.Label("Interface:2") - labelThree = Gtk.Label("Interface:3") + store = Gtk.ListStore(str) + cell = Gtk.CellRendererText() - interfaceBox = Gtk.Box(0, 10) + interfaceComboBox = Gtk.ComboBox() + interfaceComboBox.pack_start(cell, True) + interfaceComboBox.add_attribute(cell, 'text', 0) + store.append (["Item1"]) + store.append (["Item2"]) + store.append (["Item3"]) + store.append (["Item4"]) + store.append (["Item5"]) + store.append (["Item6"]) + store.append (["Item7"]) + + interfaceComboBox.set_model(store) + interfaceComboBox.set_margin_top(15) + interfaceComboBox.set_margin_end(30) + interfaceComboBox.set_active(0) + interfaceComboBox.connect("changed", self.on_button_clicked) + + + + labelOne = Gtk.Label(label="Interface:") + labelOne.set_margin_top(15) + labelOne.set_margin_start(30) + labelTwo = Gtk.Label(label="Interface:2") + labelThree = Gtk.Label(label="Interface:3") + + interfaceBox = Gtk.Box(orientation=0, spacing=100) interfaceBox.pack_start(labelOne, False, False, 0) - interfaceBox.pack_end(testbutton, True, True, 0) + interfaceBox.pack_end(interfaceComboBox, True, True, 0) - boxTwo = Gtk.Box(0, 10) + boxTwo = Gtk.Box(orientation=0, spacing=10) boxTwo.pack_start(labelTwo, True, True, 0) boxTwo.pack_end(labelThree, True, True, 0) From 8f73ac4184809ca7a8a0424eebe7fbcd808318f4 Mon Sep 17 00:00:00 2001 From: Benjamin W Crouch II Date: Sun, 19 Jan 2020 13:35:05 -0600 Subject: [PATCH 06/24] updated .gitignore to exclude .vscode dir --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index ded6067..98e3658 100644 --- a/.gitignore +++ b/.gitignore @@ -34,3 +34,6 @@ nosetests.xml .mr.developer.cfg .project .pydevproject + +# Editor Configuration Files +.vscode \ No newline at end of file From cc25a1b087530a463d53a2f9a3507e9d1e08a2b6 Mon Sep 17 00:00:00 2001 From: Benjamin W Crouch II Date: Mon, 20 Jan 2020 13:31:58 -0600 Subject: [PATCH 07/24] Completed the Combo Box and functionality to list valid configurable interfaces. Need to build UI for other configureable aspects, then once done with that bind changes made inconfig window to changes made through ifconfig. --- src/netcardmgr | 91 ++++++++++++++++++++++++++++++++----------------- src/trayicon.py | 2 +- 2 files changed, 61 insertions(+), 32 deletions(-) diff --git a/src/netcardmgr b/src/netcardmgr index 3ae11d5..1ca489b 100755 --- a/src/netcardmgr +++ b/src/netcardmgr @@ -49,7 +49,7 @@ wifiscard = wifinics.stdout.readlines()[0].rstrip() rcconf = open('/etc/rc.conf', 'r').read() notnics = ["lo", "fwe", "fwip", "tap", "plip", "pfsync", "pflog", - "tun", "sl", "faith", "ppp", "wlan", "brige", "ixautomation"] + "tun", "sl", "faith", "ppp", "wlan", "bridge", "ixautomation"] cmd = "kenv | grep rc_system" rc_system = Popen(cmd, shell=True, stdout=PIPE, universal_newlines=True) @@ -126,7 +126,7 @@ class autoConfigure(): class netCardConfigWindow(Gtk.Window): - def __init__(self): + def __init__(self, defaultactiveint): # Build Default Window Gtk.Window.__init__(self, title="Network Interface Configuration") self.set_default_size(475,450) @@ -134,56 +134,50 @@ class netCardConfigWindow(Gtk.Window): # Build Tab 1 Content # Interface Drop Down Combo Box - - store = Gtk.ListStore(str) cell = Gtk.CellRendererText() interfaceComboBox = Gtk.ComboBox() - interfaceComboBox.pack_start(cell, True) + interfaceComboBox.pack_start(cell, expand=True) interfaceComboBox.add_attribute(cell, 'text', 0) - store.append (["Item1"]) - store.append (["Item2"]) - store.append (["Item3"]) - store.append (["Item4"]) - store.append (["Item5"]) - store.append (["Item6"]) - store.append (["Item7"]) + # Add interfaces to a ListStore + store = Gtk.ListStore(str) + validinterfaces = self.enumerate_nics() + for validinterface in validinterfaces: + store.append ([validinterface]) + + # Build the UI aspects of the ComboBox, passing the interface clicked in the trayicon + # as the interface that needs to be the active one when the combo box is drawn + activeComboBoxObjectIndex = validinterfaces.index(f"{defaultactiveint}") interfaceComboBox.set_model(store) interfaceComboBox.set_margin_top(15) interfaceComboBox.set_margin_end(30) - interfaceComboBox.set_active(0) - interfaceComboBox.connect("changed", self.on_button_clicked) - - + interfaceComboBox.set_active(activeComboBoxObjectIndex) + interfaceComboBox.connect("changed", self.cbox_config_refresh) + # Build Label to sit in front of the ComboBox labelOne = Gtk.Label(label="Interface:") labelOne.set_margin_top(15) labelOne.set_margin_start(30) - labelTwo = Gtk.Label(label="Interface:2") - labelThree = Gtk.Label(label="Interface:3") + # Add both objects to a single box, which will then be added to the grid interfaceBox = Gtk.Box(orientation=0, spacing=100) interfaceBox.pack_start(labelOne, False, False, 0) interfaceBox.pack_end(interfaceComboBox, True, True, 0) - boxTwo = Gtk.Box(orientation=0, spacing=10) - boxTwo.pack_start(labelTwo, True, True, 0) - boxTwo.pack_end(labelThree, True, True, 0) - + # Build the grid, which will handle the physical layout of the UI elements. gridOne = Gtk.Grid() gridOne.set_column_homogeneous(True) gridOne.set_row_homogeneous(False) gridOne.set_column_spacing(5) gridOne.set_row_spacing(10) gridOne.attach(interfaceBox, 0, 0, 4, 1) - gridOne.attach(boxTwo, 0, 1, 4, 1) - # Build Tab 2 Content + # Placeholder for Tab 1 Content testbutton2 = Gtk.Button(label="IPv6 Stuff") testbutton2.connect("clicked", self.on_button_clicked) - # Build Tab 3 Content + # Placeholder for Tab 2 Content testbutton3 = Gtk.Button(label="VPN Stuff") testbutton3.connect("clicked", self.on_button_clicked) @@ -192,23 +186,55 @@ class netCardConfigWindow(Gtk.Window): nb.set_tab_pos(2) self.add(nb) - # Apply Tab 1 content and formatting + # Apply Tab 1 content and formatting to the notebook nb.append_page(gridOne) nb.set_tab_label_text(gridOne, "IPv4 Settings") - # Apply Tab 2 content and formatting + # Apply Tab 2 content and formatting to the notebook nb.append_page(testbutton2) nb.set_tab_label_text(testbutton2, "IPv6 Settings") - # Apply Tab 3 content and formatting + # Apply Tab 3 content and formatting to the notebook nb.append_page(testbutton3) nb.set_tab_label_text(testbutton3, "VPN") + # Need to delete this function before shippint. Placeholder for tab 2/3 functionality. def on_button_clicked(self, widget): + print(f"{widget}") + print(f"{self}") print(f"Hello World") -def openNetCardConfigwindow(): - win = netCardConfigWindow() + # Returns a list of valid configureable interfaces. + def enumerate_nics(self): + validnics = list() + confnotnics = ["lo", "fwe", "fwip", "tap", "plip", "pfsync", "pflog", + "tun", "sl", "faith", "ppp", "bridge", "ixautomation"] + confncard = 'ifconfig -l' + confnics = Popen(confncard, shell=True, stdout=PIPE, close_fds=True, universal_newlines=True) + confnetcard = confnics.stdout.readlines()[0].rstrip() + confnetcardarray = confnetcard.split(" ") + for confnic in confnetcardarray: + nicgeneralized = re.findall( "[a-zA-Z]+", confnic) + stringnicgeneralized = str(nicgeneralized).replace("'", "") + stringnicgeneralized = stringnicgeneralized.replace("[", "") + stringnicgeneralized = stringnicgeneralized.replace("]", "") + if stringnicgeneralized in confnotnics: + print(f"{confnic} was generalized to {nicgeneralized} and was found in the notnics list! " + "It will not be added to the valid configurable nic list in the netCardConfigWindow.enumerate_nics method.") + else: + validnics.append(confnic) + return(validnics) + # Used with the combo box to refresh the UI of tab 1 with active settings for the newly selected active interface. + def cbox_config_refresh(self, widget): + refreshedInterface = widget.get_active() + refreshedInterfaceName = self.enumerate_nics()[refreshedInterface] + # actions here need to refresh the values on the first tab. + print(f"Refreshing settings to match current settings on {refreshedInterface}. " + f"Interface name is {refreshedInterfaceName}") + + +def openNetCardConfigwindow(default_int): + win = netCardConfigWindow(default_int) win.connect("destroy", Gtk.main_quit) win.show_all() Gtk.main() @@ -216,6 +242,9 @@ def openNetCardConfigwindow(): if "-auto" in sys.argv: autoConfigure() elif "-configure" in sys.argv: - openNetCardConfigwindow() + confloc = sys.argv.index('-configure') + intloc = confloc + 1 + passedint = sys.argv[intloc] + openNetCardConfigwindow(passedint) else: print(f"No acceptable flags were passed to the function.") \ No newline at end of file diff --git a/src/trayicon.py b/src/trayicon.py index 758ff52..6b880fa 100755 --- a/src/trayicon.py +++ b/src/trayicon.py @@ -180,7 +180,7 @@ def wifiListMenu(self, wificard, cbssid, passes, cards): self.menu.append(avconnmenu) def configuration_window_open(self, widget, interface): - os.system( "doas netcardmgr -configure" ) + os.system( f"doas netcardmgr -configure {interface}" ) def menu_click_open(self, widget, ssid, bssid, wificard): if bssid in open(wpa_supplican).read(): From 631929d39b3b29c3a0eb5502767ebe8a5fb1a90b Mon Sep 17 00:00:00 2001 From: Benjamin W Crouch II Date: Tue, 21 Jan 2020 11:28:42 -0600 Subject: [PATCH 08/24] Added entry fields for IP addresses, but I think they need to be text boxes. Need to do more research. --- src/netcardmgr | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/src/netcardmgr b/src/netcardmgr index 1ca489b..bdaa396 100755 --- a/src/netcardmgr +++ b/src/netcardmgr @@ -165,6 +165,50 @@ class netCardConfigWindow(Gtk.Window): interfaceBox.pack_start(labelOne, False, False, 0) interfaceBox.pack_end(interfaceComboBox, True, True, 0) + # Add radio button to toggle DHCP or not + radioButton1 = Gtk.RadioButton.new_with_label(None, "DHCP") + radioButton1.set_margin_top(15) + radioButton2 = Gtk.RadioButton.new_with_label_from_widget(radioButton1, "Manual") + radioButton2.set_margin_top(15) + radioButton2.join_group(radioButton1) + + radioButtonLabel = Gtk.Label(label="IPv4 Method:") + radioButtonLabel.set_margin_top(15) + radioButtonLabel.set_margin_start(30) + + radioBox = Gtk.Box(orientation=0, spacing=50) + radioBox.set_homogeneous(False) + radioBox.pack_start(radioButtonLabel, False, False, 0) + radioBox.pack_start(radioButton1, True, False, 0) + radioBox.pack_end(radioButton2, True, True, 0) + + # Add Manual Address Field + ipInputAddressLabel = Gtk.Label(label="Address") + ipInputAddressLabel.set_margin_top(15) + + ipInputMaskLabel = Gtk.Label(label="Subnet Mask") + ipInputMaskLabel.set_margin_top(15) + + ipInputGatewayLabel = Gtk.Label(label="Gateway") + ipInputGatewayLabel.set_margin_top(15) + + ipInputAddressEntry = Gtk.Entry() + ipInputAddressEntry.set_margin_start(15) + ipInputMaskEntry = Gtk.Entry() + ipInputGatewayEntry = Gtk.Entry() + ipInputGatewayEntry.set_margin_end(15) + + ipInputBox = Gtk.Box(orientation=0, spacing=0) + ipInputBox.set_homogeneous(True) + ipInputBox.pack_start(ipInputAddressLabel, False, False, 0) + ipInputBox.pack_start(ipInputMaskLabel, False, False, 0) + ipInputBox.pack_start(ipInputGatewayLabel, False, False, 0) + + ipEntryBox = Gtk.Box(orientation=0, spacing=30) + ipEntryBox.pack_start(ipInputAddressEntry, False, False, 0) + ipEntryBox.pack_start(ipInputMaskEntry, False, False, 0) + ipEntryBox.pack_start(ipInputGatewayEntry, False, False, 0) + # Build the grid, which will handle the physical layout of the UI elements. gridOne = Gtk.Grid() gridOne.set_column_homogeneous(True) @@ -172,6 +216,9 @@ class netCardConfigWindow(Gtk.Window): gridOne.set_column_spacing(5) gridOne.set_row_spacing(10) gridOne.attach(interfaceBox, 0, 0, 4, 1) + gridOne.attach(radioBox, 0, 1, 4, 1) + gridOne.attach(ipInputBox, 0, 2, 4, 1) + gridOne.attach(ipEntryBox, 0, 3, 4, 1) # Placeholder for Tab 1 Content testbutton2 = Gtk.Button(label="IPv6 Stuff") From a43b02831d8461aa136b06bafc865aa333d0cf6f Mon Sep 17 00:00:00 2001 From: Benjamin W Crouch II Date: Thu, 23 Jan 2020 11:57:32 -0600 Subject: [PATCH 09/24] Added remaining fields to the IPv4 configuration tab. Need to add a save and cancle button, then connect actions to ifconfig calls. --- src/netcardmgr | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/src/netcardmgr b/src/netcardmgr index bdaa396..274a6db 100755 --- a/src/netcardmgr +++ b/src/netcardmgr @@ -209,6 +209,33 @@ class netCardConfigWindow(Gtk.Window): ipEntryBox.pack_start(ipInputMaskEntry, False, False, 0) ipEntryBox.pack_start(ipInputGatewayEntry, False, False, 0) + # Add DNS Server Settings + dnsLabel = Gtk.Label(label="DNS Servers: ") + dnsLabel.set_margin_top(15) + dnsLabel.set_margin_end(58) + dnsLabel.set_margin_start(30) + + dnsEntry = Gtk.Entry() + dnsEntry.set_margin_end(30) + + dnsEntryBox = Gtk.Box(orientation=0, spacing=0) + dnsEntryBox.pack_start(dnsLabel, False, False, 0) + dnsEntryBox.pack_end(dnsEntry, True, True, 0) + + # Add Search Domain Settings + + searchLabel = Gtk.Label(label="Search domains: ") + searchLabel.set_margin_top(15) + searchLabel.set_margin_end(30) + searchLabel.set_margin_start(30) + + searchEntry = Gtk.Entry() + searchEntry.set_margin_end(30) + + searchBox = Gtk.Box(orientation=0, spacing=0) + searchBox.pack_start(searchLabel, False, False, 0) + searchBox.pack_end(searchEntry, True, True, 0) + # Build the grid, which will handle the physical layout of the UI elements. gridOne = Gtk.Grid() gridOne.set_column_homogeneous(True) @@ -219,6 +246,8 @@ class netCardConfigWindow(Gtk.Window): gridOne.attach(radioBox, 0, 1, 4, 1) gridOne.attach(ipInputBox, 0, 2, 4, 1) gridOne.attach(ipEntryBox, 0, 3, 4, 1) + gridOne.attach(dnsEntryBox, 0, 4, 4, 1) + gridOne.attach(searchBox, 0, 5, 4, 1) # Placeholder for Tab 1 Content testbutton2 = Gtk.Button(label="IPv6 Stuff") From d36a15f12a4e0619385cdbd8f5095e3500815613 Mon Sep 17 00:00:00 2001 From: Benjamin W Crouch II Date: Fri, 24 Jan 2020 09:20:36 -0600 Subject: [PATCH 10/24] Finally happy with the rough UI layout. Now I just need to associate actions on the UI with methods, most of which will probably be in the netapi file. --- src/netcardmgr | 182 ++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 158 insertions(+), 24 deletions(-) diff --git a/src/netcardmgr b/src/netcardmgr index 274a6db..8a13052 100755 --- a/src/netcardmgr +++ b/src/netcardmgr @@ -127,9 +127,9 @@ class autoConfigure(): class netCardConfigWindow(Gtk.Window): def __init__(self, defaultactiveint): - # Build Default Window + ### Build Default Window Gtk.Window.__init__(self, title="Network Interface Configuration") - self.set_default_size(475,450) + self.set_default_size(475,400) # Build Tab 1 Content @@ -230,7 +230,9 @@ class netCardConfigWindow(Gtk.Window): searchLabel.set_margin_start(30) searchEntry = Gtk.Entry() + searchEntry.set_margin_top(21) searchEntry.set_margin_end(30) + searchEntry.set_margin_bottom(30) searchBox = Gtk.Box(orientation=0, spacing=0) searchBox.pack_start(searchLabel, False, False, 0) @@ -249,36 +251,162 @@ class netCardConfigWindow(Gtk.Window): gridOne.attach(dnsEntryBox, 0, 4, 4, 1) gridOne.attach(searchBox, 0, 5, 4, 1) - # Placeholder for Tab 1 Content - testbutton2 = Gtk.Button(label="IPv6 Stuff") - testbutton2.connect("clicked", self.on_button_clicked) - - # Placeholder for Tab 2 Content - testbutton3 = Gtk.Button(label="VPN Stuff") - testbutton3.connect("clicked", self.on_button_clicked) + ## Build Tab 2 Content + + ## Interface Drop Down Combo Box + cell6 = Gtk.CellRendererText() + + interfaceComboBox6 = Gtk.ComboBox() + interfaceComboBox6.pack_start(cell6, expand=True) + interfaceComboBox6.add_attribute(cell6, 'text', 0) + + ## Add interfaces to a ListStore + store6 = Gtk.ListStore(str) + validinterfaces6 = self.enumerate_nics() + for validinterface6 in validinterfaces6: + store6.append ([validinterface6]) + + ## Build the UI aspects of the ComboBox, passing the interface clicked in the trayicon + ## as the interface that needs to be the active one when the combo box is drawn + activeComboBoxObjectIndex6 = validinterfaces6.index(f"{defaultactiveint}") + interfaceComboBox6.set_model(store) + interfaceComboBox6.set_margin_top(15) + interfaceComboBox6.set_margin_end(30) + interfaceComboBox6.set_active(activeComboBoxObjectIndex6) + interfaceComboBox6.connect("changed", self.cbox_config_refresh) + + ## Build Label to sit in front of the ComboBox + labelOne6 = Gtk.Label(label="Interface:") + labelOne6.set_margin_top(15) + labelOne6.set_margin_start(30) + + ## Add both objects to a single box, which will then be added to the grid + interfaceBox6 = Gtk.Box(orientation=0, spacing=100) + interfaceBox6.pack_start(labelOne6, False, False, 0) + interfaceBox6.pack_end(interfaceComboBox6, True, True, 0) + + ## Add radio button to toggle DHCP or not + radioButton1V6 = Gtk.RadioButton.new_with_label(None, "SLAAC") + radioButton1V6.set_margin_top(15) + radioButton2V6 = Gtk.RadioButton.new_with_label_from_widget(radioButton1V6, "Manual") + radioButton2V6.set_margin_top(15) + radioButton2V6.join_group(radioButton1V6) + + radioButtonLabel6 = Gtk.Label(label="IPv4 Method:") + radioButtonLabel6.set_margin_top(15) + radioButtonLabel6.set_margin_start(30) + + radioBox6 = Gtk.Box(orientation=0, spacing=50) + radioBox6.set_homogeneous(False) + radioBox6.pack_start(radioButtonLabel6, False, False, 0) + radioBox6.pack_start(radioButton1V6, True, False, 0) + radioBox6.pack_end(radioButton2V6, True, True, 0) + + ## Add Manual Address Field + ipInputAddressLabel6 = Gtk.Label(label="Address") + ipInputAddressLabel6.set_margin_top(15) + + ipInputMaskLabel6 = Gtk.Label(label="Subnet Mask") + ipInputMaskLabel6.set_margin_top(15) + + ipInputGatewayLabel6 = Gtk.Label(label="Gateway") + ipInputGatewayLabel6.set_margin_top(15) + + ipInputAddressEntry6 = Gtk.Entry() + ipInputAddressEntry6.set_margin_start(15) + ipInputMaskEntry6 = Gtk.Entry() + ipInputGatewayEntry6 = Gtk.Entry() + ipInputGatewayEntry6.set_margin_end(15) + + ipInputBox6 = Gtk.Box(orientation=0, spacing=0) + ipInputBox6.set_homogeneous(True) + ipInputBox6.pack_start(ipInputAddressLabel6, False, False, 0) + ipInputBox6.pack_start(ipInputMaskLabel6, False, False, 0) + ipInputBox6.pack_start(ipInputGatewayLabel6, False, False, 0) + + ipEntryBox6 = Gtk.Box(orientation=0, spacing=30) + ipEntryBox6.pack_start(ipInputAddressEntry6, False, False, 0) + ipEntryBox6.pack_start(ipInputMaskEntry6, False, False, 0) + ipEntryBox6.pack_start(ipInputGatewayEntry6, False, False, 0) + + ## Add DNS Server Settings + dnsLabel6 = Gtk.Label(label="DNS Servers: ") + dnsLabel6.set_margin_top(15) + dnsLabel6.set_margin_end(58) + dnsLabel6.set_margin_start(30) + + dnsEntry6 = Gtk.Entry() + dnsEntry6.set_margin_end(30) + + dnsEntryBox6 = Gtk.Box(orientation=0, spacing=0) + dnsEntryBox6.pack_start(dnsLabel6, False, False, 0) + dnsEntryBox6.pack_end(dnsEntry6, True, True, 0) + + ## Add Search Domain Settings + + searchLabel6 = Gtk.Label(label="Search domains: ") + searchLabel6.set_margin_top(15) + searchLabel6.set_margin_end(30) + searchLabel6.set_margin_start(30) + + searchEntry6 = Gtk.Entry() + searchEntry6.set_margin_top(21) + searchEntry6.set_margin_end(30) + searchEntry6.set_margin_bottom(30) + + searchBox6 = Gtk.Box(orientation=0, spacing=0) + searchBox6.pack_start(searchLabel6, False, False, 0) + searchBox6.pack_end(searchEntry6, True, True, 0) + + ## Build the grid, which will handle the physical layout of the UI elements. + gridOne6 = Gtk.Grid() + gridOne6.set_column_homogeneous(True) + gridOne6.set_row_homogeneous(False) + gridOne6.set_column_spacing(5) + gridOne6.set_row_spacing(10) + gridOne6.attach(interfaceBox6, 0, 0, 4, 1) + gridOne6.attach(radioBox6, 0, 1, 4, 1) + gridOne6.attach(ipInputBox6, 0, 2, 4, 1) + gridOne6.attach(ipEntryBox6, 0, 3, 4, 1) + gridOne6.attach(dnsEntryBox6, 0, 4, 4, 1) + gridOne6.attach(searchBox6, 0, 5, 4, 1) + + ### Build Notebook - # Build Notebook nb = Gtk.Notebook() + nb.set_margin_start(10) + nb.set_margin_end(10) + nb.set_margin_top(10) + nb.set_margin_bottom(10) nb.set_tab_pos(2) - self.add(nb) + + ### Build Save & Cancel Buttons + + saveButton = Gtk.Button(label="Save...") + saveButton.set_margin_bottom(10) + saveButton.set_margin_start(10) + saveButton.connect("clicked",self.commit_pending_changes) + cancelButton = Gtk.Button(label="Cancel...") + cancelButton.set_margin_bottom(10) + cancelButton.connect("clicked", self.discard_pending_changes) + buttonsWindow = Gtk.Box(orientation=0, spacing=10) + buttonsWindow.pack_start(saveButton, False, False, 0) + buttonsWindow.pack_start(cancelButton, False, False, 0) # Apply Tab 1 content and formatting to the notebook nb.append_page(gridOne) nb.set_tab_label_text(gridOne, "IPv4 Settings") - # Apply Tab 2 content and formatting to the notebook - nb.append_page(testbutton2) - nb.set_tab_label_text(testbutton2, "IPv6 Settings") + ## Apply Tab 2 content and formatting to the notebook + nb.append_page(gridOne6) + nb.set_tab_label_text(gridOne6, "IPv6 Settings") - # Apply Tab 3 content and formatting to the notebook - nb.append_page(testbutton3) - nb.set_tab_label_text(testbutton3, "VPN") + ### Put all the widgets together into one window + mainBox = Gtk.Box(orientation=1, spacing=0) + mainBox.pack_start(nb, False, False, 0) + mainBox.pack_start(buttonsWindow, False, False, 0) + self.add(mainBox) - # Need to delete this function before shippint. Placeholder for tab 2/3 functionality. - def on_button_clicked(self, widget): - print(f"{widget}") - print(f"{self}") - print(f"Hello World") # Returns a list of valid configureable interfaces. def enumerate_nics(self): @@ -304,9 +432,15 @@ class netCardConfigWindow(Gtk.Window): def cbox_config_refresh(self, widget): refreshedInterface = widget.get_active() refreshedInterfaceName = self.enumerate_nics()[refreshedInterface] - # actions here need to refresh the values on the first tab. + # actions here need to refresh the values on the first two tabs. print(f"Refreshing settings to match current settings on {refreshedInterface}. " - f"Interface name is {refreshedInterfaceName}") + f"Interface name is {refreshedInterfaceName}") + + def commit_pending_changes(self, widget): + print(f"commit_pending_changes_goes_here") + + def discard_pending_changes(self, widget): + print(f"discard_pending_changes_goes_here") def openNetCardConfigwindow(default_int): From 0b3357494fdba0b4b0a06762f7aacba6e3643cf2 Mon Sep 17 00:00:00 2001 From: Benjamin W Crouch II Date: Mon, 27 Jan 2020 11:26:32 -0600 Subject: [PATCH 11/24] Almost completely one with the get-interface-settings function. Having issues with it detecting DHCP on the wlan0 interface, but will have to fix this later. --- src/netcardmgr | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/src/netcardmgr b/src/netcardmgr index 8a13052..e4070b8 100755 --- a/src/netcardmgr +++ b/src/netcardmgr @@ -36,6 +36,7 @@ from subprocess import Popen, PIPE import os import re import sys +import subprocess from time import sleep ncard = 'ifconfig -l' @@ -407,6 +408,9 @@ class netCardConfigWindow(Gtk.Window): mainBox.pack_start(buttonsWindow, False, False, 0) self.add(mainBox) + #### Run any functions that need to execute once at window creation + self.cbox_config_refresh(interfaceComboBox) + # Returns a list of valid configureable interfaces. def enumerate_nics(self): @@ -435,6 +439,61 @@ class netCardConfigWindow(Gtk.Window): # actions here need to refresh the values on the first two tabs. print(f"Refreshing settings to match current settings on {refreshedInterface}. " f"Interface name is {refreshedInterfaceName}") + self.get_current_interface_settings(refreshedInterfaceName) + + def get_current_interface_settings(self, active_int): + # Need to accurately determine if a wlanN interface is using DHCP + aInt = str(active_int) + + DHCPStatus = os.path.exists(f"/var/db/dhclient.leases.{aInt}") + if DHCPStatus is True: + DHCPStatusOutput = "DHCP" + else: + DHCPStatusOutput = "Manual" + + ifconfigaInt = f"ifconfig -f inet:dotted {aInt}" + ifconfigaIntOutput = subprocess.check_output(ifconfigaInt.split(" ")) + aIntIP = re.findall('inet [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+',str(ifconfigaIntOutput)) + aIntIPStrip = str(aIntIP).replace("inet ", "") + aIntIPStrip = str(aIntIPStrip).replace("'", "") + aIntIPStrip = str(aIntIPStrip).replace("[", "") + aIntIPStrip = str(aIntIPStrip).replace("]", "") + aIntMask = re.findall('netmask [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+',str(ifconfigaIntOutput)) + aIntMaskStrip = str(aIntMask).replace("netmask ", "") + aIntMaskStrip = str(aIntMaskStrip).replace("'", "") + aIntMaskStrip = str(aIntMaskStrip).replace("[", "") + aIntMaskStrip = str(aIntMaskStrip).replace("]", "") + aIntGateway = re.findall('broadcast [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+',str(ifconfigaIntOutput)) + aIntGatewayStrip = str(aIntGateway).replace("broadcast ", "") + aIntGatewayStrip = str(aIntGatewayStrip).replace("'", "") + aIntGatewayStrip = str(aIntGatewayStrip).replace("[", "") + aIntGatewayStrip = str(aIntGatewayStrip).replace("]", "") + + aIntDHCP = f"resolvconf -l {aInt}.dhcp" + aIntDHCPResults = subprocess.check_output(aIntDHCP.split(" ")) + DNSMatch = re.findall('nameserver [0-9]\.[0-9]\.[0-9]\.[0-9]' ,str(aIntDHCPResults)) + + SearchDomainMatch = re.findall('search [a-zA-Z.]*', str(aIntDHCPResults)) + SearchDomainMatchStrip = str(SearchDomainMatch).replace("search ","") + SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("'", "") + SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("[", "") + SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("]", "") + + currentSettings = {} + currentSettings["Active Interface"] = active_int + currentSettings["Address Assignment Method"] = DHCPStatusOutput + currentSettings["Interface IP"] = aIntIPStrip + currentSettings["Interface Subnet Mask"] = aIntMaskStrip + currentSettings["Default Gateway"] = aIntGatewayStrip + #[currentSettings.append(str(DNSServer).replace("nameserver ", "")) for DNSServer in DNSMatch] + currentSettings["Search Domain"] = SearchDomainMatchStrip + i = 1 + while i <= len(DNSMatch): + currentSettings[f"DNS Server {i}"] = str(DNSMatch[(i-1)]).replace("nameserver ", "") + i = i + 1 + + print(f"Current settings are below:") + print(f"{currentSettings}") def commit_pending_changes(self, widget): print(f"commit_pending_changes_goes_here") From 8715b0316152c29369fb3e7ced27f98dbc9e6c01 Mon Sep 17 00:00:00 2001 From: Benjamin W Crouch II Date: Wed, 5 Feb 2020 09:26:33 -0600 Subject: [PATCH 12/24] Got the screen to print the initial data to the window with the current settings, but I'm having a hard time updating the window. May need to transform the currentSettings Dict into another class or something along those lines. --- src/netcardmgr | 125 ++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 104 insertions(+), 21 deletions(-) diff --git a/src/netcardmgr b/src/netcardmgr index e4070b8..f8db53c 100755 --- a/src/netcardmgr +++ b/src/netcardmgr @@ -125,6 +125,7 @@ class autoConfigure(): sleep(1) wlanNum += 1 +currentSettings = {} class netCardConfigWindow(Gtk.Window): def __init__(self, defaultactiveint): @@ -141,6 +142,7 @@ class netCardConfigWindow(Gtk.Window): interfaceComboBox.pack_start(cell, expand=True) interfaceComboBox.add_attribute(cell, 'text', 0) + # Add interfaces to a ListStore store = Gtk.ListStore(str) validinterfaces = self.enumerate_nics() @@ -154,6 +156,7 @@ class netCardConfigWindow(Gtk.Window): interfaceComboBox.set_margin_top(15) interfaceComboBox.set_margin_end(30) interfaceComboBox.set_active(activeComboBoxObjectIndex) + self.cbox_config_refresh(interfaceComboBox) interfaceComboBox.connect("changed", self.cbox_config_refresh) # Build Label to sit in front of the ComboBox @@ -171,6 +174,10 @@ class netCardConfigWindow(Gtk.Window): radioButton1.set_margin_top(15) radioButton2 = Gtk.RadioButton.new_with_label_from_widget(radioButton1, "Manual") radioButton2.set_margin_top(15) + if currentSettings["Address Assignment Method"] == "DHCP": + radioButton1.set_active(True) + else: + radioButton2.set_active(True) radioButton2.join_group(radioButton1) radioButtonLabel = Gtk.Label(label="IPv4 Method:") @@ -195,9 +202,14 @@ class netCardConfigWindow(Gtk.Window): ipInputAddressEntry = Gtk.Entry() ipInputAddressEntry.set_margin_start(15) + ipInputAddressEntry.set_text(currentSettings["Interface IP"]) + ipInputMaskEntry = Gtk.Entry() + ipInputMaskEntry.set_text(currentSettings["Interface Subnet Mask"]) + ipInputGatewayEntry = Gtk.Entry() ipInputGatewayEntry.set_margin_end(15) + ipInputGatewayEntry.set_text(currentSettings["Default Gateway"]) ipInputBox = Gtk.Box(orientation=0, spacing=0) ipInputBox.set_homogeneous(True) @@ -218,6 +230,15 @@ class netCardConfigWindow(Gtk.Window): dnsEntry = Gtk.Entry() dnsEntry.set_margin_end(30) + DNSList = [(key, value) for key, value in currentSettings.items() if key.startswith("DNS Server")] + i = 0 + DNSString = "" + while i < len(DNSList): + DNSString = DNSString + DNSList[i][i + 1] + if i + 1 < len(DNSList): + DNSString = DNSString + "," + i = i + 1 + dnsEntry.set_text(DNSString) dnsEntryBox = Gtk.Box(orientation=0, spacing=0) dnsEntryBox.pack_start(dnsLabel, False, False, 0) @@ -234,6 +255,7 @@ class netCardConfigWindow(Gtk.Window): searchEntry.set_margin_top(21) searchEntry.set_margin_end(30) searchEntry.set_margin_bottom(30) + searchEntry.set_text(currentSettings["Search Domain"]) searchBox = Gtk.Box(orientation=0, spacing=0) searchBox.pack_start(searchLabel, False, False, 0) @@ -440,50 +462,106 @@ class netCardConfigWindow(Gtk.Window): print(f"Refreshing settings to match current settings on {refreshedInterface}. " f"Interface name is {refreshedInterfaceName}") self.get_current_interface_settings(refreshedInterfaceName) + self.display_current_interface_settings(widget) def get_current_interface_settings(self, active_int): # Need to accurately determine if a wlanN interface is using DHCP aInt = str(active_int) DHCPStatus = os.path.exists(f"/var/db/dhclient.leases.{aInt}") - if DHCPStatus is True: - DHCPStatusOutput = "DHCP" + print(f"dhcpstatus return value = {DHCPStatus}") + if DHCPStatus is False: + RCConf = open("/etc/rc.conf", "r").read() + DHCPSearch = re.findall(f"^ifconfig_{aInt}=\".*DHCP", RCConf) + print(f"DHCPSearch is {DHCPSearch} and the length is {len(DHCPSearch)}") + if len(DHCPSearch) < 1: + DHCPStatusOutput = "Manual" + else: + DHCPStatusOutput = "DHCP" else: - DHCPStatusOutput = "Manual" + DHCPStatusOutput = "DHCP" + + print(f"DHCPStatusOutput = {DHCPStatusOutput}") ifconfigaInt = f"ifconfig -f inet:dotted {aInt}" ifconfigaIntOutput = subprocess.check_output(ifconfigaInt.split(" ")) - aIntIP = re.findall('inet [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+',str(ifconfigaIntOutput)) + aIntIP = re.findall('inet [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+',str(ifconfigaIntOutput))[0] aIntIPStrip = str(aIntIP).replace("inet ", "") aIntIPStrip = str(aIntIPStrip).replace("'", "") aIntIPStrip = str(aIntIPStrip).replace("[", "") aIntIPStrip = str(aIntIPStrip).replace("]", "") - aIntMask = re.findall('netmask [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+',str(ifconfigaIntOutput)) + aIntMask = re.findall('netmask [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+',str(ifconfigaIntOutput))[0] aIntMaskStrip = str(aIntMask).replace("netmask ", "") aIntMaskStrip = str(aIntMaskStrip).replace("'", "") aIntMaskStrip = str(aIntMaskStrip).replace("[", "") aIntMaskStrip = str(aIntMaskStrip).replace("]", "") - aIntGateway = re.findall('broadcast [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+',str(ifconfigaIntOutput)) - aIntGatewayStrip = str(aIntGateway).replace("broadcast ", "") - aIntGatewayStrip = str(aIntGatewayStrip).replace("'", "") - aIntGatewayStrip = str(aIntGatewayStrip).replace("[", "") - aIntGatewayStrip = str(aIntGatewayStrip).replace("]", "") - - aIntDHCP = f"resolvconf -l {aInt}.dhcp" - aIntDHCPResults = subprocess.check_output(aIntDHCP.split(" ")) - DNSMatch = re.findall('nameserver [0-9]\.[0-9]\.[0-9]\.[0-9]' ,str(aIntDHCPResults)) - - SearchDomainMatch = re.findall('search [a-zA-Z.]*', str(aIntDHCPResults)) - SearchDomainMatchStrip = str(SearchDomainMatch).replace("search ","") - SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("'", "") - SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("[", "") - SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("]", "") + aIntBroadcast = re.findall('broadcast [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+',str(ifconfigaIntOutput))[0] + aIntBroadcastStrip = str(aIntBroadcast).replace("broadcast ", "") + aIntBroadcastStrip = str(aIntBroadcastStrip).replace("'", "") + aIntBroadcastStrip = str(aIntBroadcastStrip).replace("[", "") + aIntBroadcastStrip = str(aIntBroadcastStrip).replace("]", "") + + if (DHCPStatusOutput == "DHCP"): + print(f"{DHCPStatusOutput}") + DHClientFileTest = os.path.exists(f"/var/db/dhclient.leases.{aInt}") + if DHClientFileTest == False: + print(f"dhclientfiletest = {DHClientFileTest}") + RenewDHCP = f"dhclient {aInt}" + RenewDHCPOutput = subprocess.check_output(RenewDHCP.split(" ")) + sleep(5) + DHClientFileTest = os.path.exists(f"/var/db/dhclient.leases.{aInt}") + if DHClientFileTest == False: + print(f"DHCP is enabled, but we're unable to read the lease file a /var/db/dhclient.leases.{aInt}") + aIntGatewayStrip = "" + else: + DHCPLeaseInfo = open(f"/var/db/dhclient.leases.{aInt}", "r").read() + aIntGateway = re.findall("option routers [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+;", DHCPLeaseInfo)[0] + aIntGatewayStrip = str(aIntGateway).replace("option routers ", "") + aIntGatewayStrip = str(aIntGatewayStrip).replace("'","") + aIntGatewayStrip = str(aIntGatewayStrip).replace("[", "") + aIntGatewayStrip = str(aIntGatewayStrip).replace("]","") + aIntGatewayStrip = str(aIntGatewayStrip).replace(";","") + + aIntDHCP = f"resolvconf -l {aInt}.dhcp" + aIntDHCPResults = subprocess.check_output(aIntDHCP.split(" ")) + DNSMatch = re.findall('nameserver [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' ,str(aIntDHCPResults)) + + SearchDomainMatch = re.findall('search [a-zA-Z.]*', str(aIntDHCPResults)) + if len(SearchDomainMatch) < 1: + RCConfDomainSearch = open('/etc/resolv.conf', 'r').read() + SearchDomainMatch = re.findall('domain (.*)', RCConfDomainSearch) + SearchDomainMatchStrip = str(SearchDomainMatch).replace("domain ","") + SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("'", "") + SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("[", "") + SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("]", "") + + else: + RRConfGatewaySearch = open('/etc/rc.conf', 'r').read() + RRConfGatewayResults = re.findall('defaultrouter="[0-9]+\.[0-9]+\.[0-9]+\.[0-9]"', RRConfGatewaySearch) + aIntGatewayStrip = str(RRConfGatewayResults).replace('defaultrouter="', "") + aIntGatewayStrip = str(aIntGatewayStrip).replace('"', "") + aIntGatewayStrip = str(aIntGatewayStrip).replace('[', "") + aIntGatewayStrip = str(aIntGatewayStrip).replace(']',"") + aIntGatewayStrip = str(aIntGatewayStrip).replace("'","") + + DefaultDNSServers = open('/etc/resolv.conf').read() + DNSMatch = re.findall('nameserver [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' ,str(DefaultDNSServers)) + + RCConfDomainSearch = open('/etc/resolv.conf', 'r').read() + SearchDomainMatch = re.findall('domain (.*)', RCConfDomainSearch) + SearchDomainMatchStrip = str(SearchDomainMatch).replace("domain ","") + SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("'", "") + SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("[", "") + SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("]", "") + + - currentSettings = {} + #currentSettings = {} currentSettings["Active Interface"] = active_int currentSettings["Address Assignment Method"] = DHCPStatusOutput currentSettings["Interface IP"] = aIntIPStrip currentSettings["Interface Subnet Mask"] = aIntMaskStrip + currentSettings["Broadcast Address"] = aIntBroadcastStrip currentSettings["Default Gateway"] = aIntGatewayStrip #[currentSettings.append(str(DNSServer).replace("nameserver ", "")) for DNSServer in DNSMatch] currentSettings["Search Domain"] = SearchDomainMatchStrip @@ -495,11 +573,16 @@ class netCardConfigWindow(Gtk.Window): print(f"Current settings are below:") print(f"{currentSettings}") + def display_current_interface_settings(self, widget): + print(f"display_current_interface_settings_go_here") + def commit_pending_changes(self, widget): print(f"commit_pending_changes_goes_here") def discard_pending_changes(self, widget): print(f"discard_pending_changes_goes_here") + currentSettings["Interface IP"] = "poo" + def openNetCardConfigwindow(default_int): From e111151aebcc302e3adb5579cd751a5a57cbe216 Mon Sep 17 00:00:00 2001 From: Benjamin W Crouch II Date: Wed, 5 Feb 2020 09:27:16 -0600 Subject: [PATCH 13/24] typo change. --- src/netcardmgr | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/netcardmgr b/src/netcardmgr index f8db53c..47d2bd1 100755 --- a/src/netcardmgr +++ b/src/netcardmgr @@ -581,7 +581,7 @@ class netCardConfigWindow(Gtk.Window): def discard_pending_changes(self, widget): print(f"discard_pending_changes_goes_here") - currentSettings["Interface IP"] = "poo" + From d59c36d68ca20e6956b097566383ebb9b231ee60 Mon Sep 17 00:00:00 2001 From: ericbsd Date: Wed, 16 Jun 2021 17:39:54 -0300 Subject: [PATCH 14/24] renamed net card and sent it has a library fixed netCardConfigWindow --- setup.py | 5 +- src/{netcardmgr => netcardmgr.py} | 79 +------------------------------ src/trayicon.py | 4 +- 3 files changed, 7 insertions(+), 81 deletions(-) rename src/{netcardmgr => netcardmgr.py} (87%) diff --git a/setup.py b/setup.py index fdca885..56fc754 100755 --- a/setup.py +++ b/setup.py @@ -25,7 +25,8 @@ def datafilelist(installbase, sourcebase): share_networkmgr = [ 'src/net_api.py', - 'src/trayicon.py' + 'src/trayicon.py', + 'src/netcardmgr.py' ] data_files = [ @@ -51,7 +52,7 @@ def datafilelist(installbase, sourcebase): package_dir={'': '.'}, data_files=data_files, install_requires=['setuptools'], - scripts=['networkmgr', 'src/netcardmgr', 'src/setup-nic'] + scripts=['networkmgr', 'src/setup-nic'] ) run('gtk-update-icon-cache -f /usr/local/share/icons/hicolor', shell=True) diff --git a/src/netcardmgr b/src/netcardmgr.py similarity index 87% rename from src/netcardmgr rename to src/netcardmgr.py index 6370e4a..0a1d6f1 100755 --- a/src/netcardmgr +++ b/src/netcardmgr.py @@ -6,7 +6,6 @@ from subprocess import Popen, PIPE import os import re -import sys import subprocess from time import sleep @@ -57,70 +56,6 @@ restart_network = f'{rc}service {network} restart' - -class autoConfigure(): - - def __init__(self): - for line in netcard.split(): - card = line.rstrip() - # VLAN tags in ifconfig are delimited by period - # but in rc.conf delimiter is underscore - card = card.replace(".", "_") - nc = re.sub(r'\d+', '', line.rstrip()) - if nc not in notnics: - if f'ifconfig_{card}=' in (rcconf or rcconflocal): - print("Your wired network card is already configured.") - else: - rc = open('/etc/rc.conf', 'a') - rc.writelines(f'ifconfig_{card}="DHCP"\n') - rc.close() - sleep(1) - os.system(restart_network) - sleep(1) - if os.path.exists("/sbin/openrc") is True: - cmd = f"rc-service dhcpcd.{card} restart" - os.system(cmd) - print("Your wired network card is configured.") - - for card in wifiscard.split(): - for wlanNum in range(0, 9): - if f'wlan{wlanNum}' not in (rcconf + rcconflocal): - break - if f'wlans_{card}=' in (rcconf + rcconflocal): - print("Your wifi network card is already configured.") - if not os.path.exists('/etc/wpa_supplicant.conf'): - open('/etc/wpa_supplicant.conf', 'a').close() - os.system('chown root:wheel /etc/wpa_supplicant.conf') - os.system('chmod 765 /etc/wpa_supplicant.conf') - else: - os.system('chown root:wheel /etc/wpa_supplicant.conf') - os.system('chmod 765 /etc/wpa_supplicant.conf') - else: - rc = open('/etc/rc.conf', 'a') - rc.writelines(f'wlans_{card}="wlan{wlanNum}"\n') - rc.writelines(f'ifconfig_wlan{wlanNum}="WPA DHCP"\n') - rc.close() - if not os.path.exists('/etc/wpa_supplicant.conf'): - open('/etc/wpa_supplicant.conf', 'a').close() - os.system('chown root:wheel /etc/wpa_supplicant.conf') - os.system('chmod 765 /etc/wpa_supplicant.conf') - sleep(1) - os.system(restart_network) - sleep(1) - nicslist = 'ifconfig -l' - ifconfig = Popen(nicslist, shell=True, stdout=PIPE, - close_fds=True, universal_newlines=True) - cardlist = ifconfig.stdout.read() - if f'wlan{wlanNum}' not in cardlist: - sleep(1) - os.system(restart_network) - sleep(1) - os.system(f'ifconfig wlan{wlanNum} up scan') - os.system(f'ifconfig wlan{wlanNum} up scan') - sleep(1) - wlanNum += 1 - - currentSettings = {} @@ -228,10 +163,11 @@ def __init__(self, defaultactiveint): dnsEntry = Gtk.Entry() dnsEntry.set_margin_end(30) DNSList = [(key, value) for key, value in currentSettings.items() if key.startswith("DNS Server")] + print(DNSList) i = 0 DNSString = "" while i < len(DNSList): - DNSString = DNSString + DNSList[i][i + 1] + DNSString = DNSString + DNSList[i][1] if i + 1 < len(DNSList): DNSString = DNSString + "," i = i + 1 @@ -582,14 +518,3 @@ def openNetCardConfigwindow(default_int): win.connect("destroy", Gtk.main_quit) win.show_all() Gtk.main() - - -if "-auto" in sys.argv: - autoConfigure() -elif "-configure" in sys.argv: - confloc = sys.argv.index('-configure') - intloc = confloc + 1 - passedint = sys.argv[intloc] - openNetCardConfigwindow(passedint) -else: - print("No acceptable flags were passed to the function.") diff --git a/src/trayicon.py b/src/trayicon.py index 011c00c..8670b79 100755 --- a/src/trayicon.py +++ b/src/trayicon.py @@ -4,7 +4,6 @@ gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GObject, GLib from time import sleep -import os import threading import _thread from sys import path @@ -26,6 +25,7 @@ delete_ssid_wpa_supplicant_config, wlan_status ) +from netcardmgr import openNetCardConfigwindow encoding = locale.getpreferredencoding() threadBreak = False @@ -190,7 +190,7 @@ def wifiListMenu(self, wificard, cssid, passes, cards): self.menu.append(avconnmenu) def configuration_window_open(self, widget, interface): - os.system(f"doas netcardmgr -configure {interface}") + openNetCardConfigwindow(interface) def menu_click_open(self, widget, ssid, wificard): if f'"{ssid}"' in open("/etc/wpa_supplicant.conf").read(): From 2bb698dfbef634ba35017eba11f98199eaeb09f6 Mon Sep 17 00:00:00 2001 From: ericbsd Date: Mon, 21 Feb 2022 14:25:40 -0400 Subject: [PATCH 15/24] Move netcardmgr to share_networkmgr --- setup.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index eb5a11a..5e88b74 100755 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ from setuptools import setup from subprocess import run -__VERSION__ = '6.1' +__VERSION__ = '6.2' PROGRAM_VERSION = __VERSION__ prefix = '/usr/local' if system() == 'FreeBSD' else sys.prefix @@ -27,7 +27,8 @@ def datafilelist(installbase, sourcebase): 'src/auto-switch.py', 'src/net_api.py', 'src/setup-nic.py', - 'src/trayicon.py' + 'src/trayicon.py', + 'src/netcardmgr.py' ] data_files = [ @@ -53,7 +54,7 @@ def datafilelist(installbase, sourcebase): package_dir={'': '.'}, data_files=data_files, install_requires=['setuptools'], - scripts=['networkmgr', 'src/netcardmgr'] + scripts=['networkmgr'] ) run('gtk-update-icon-cache -f /usr/local/share/icons/hicolor', shell=True) From ea3d33429bc968b0c80aa094e9f397b052092431 Mon Sep 17 00:00:00 2001 From: ericbsd Date: Mon, 21 Feb 2022 16:28:07 -0400 Subject: [PATCH 16/24] Remove OpenRC support from networkmgr --- src/net_api.py | 61 +++++++++---------------------------------------- src/trayicon.py | 21 ++++++++--------- 2 files changed, 20 insertions(+), 62 deletions(-) diff --git a/src/net_api.py b/src/net_api.py index fe682a6..030522b 100755 --- a/src/net_api.py +++ b/src/net_api.py @@ -36,19 +36,6 @@ path.append("/usr/local/share/networkmgr") -cmd = "kenv | grep rc_system" -rc_system = Popen(cmd, shell=True, stdout=PIPE, universal_newlines=True) - -if 'openrc' in rc_system.stdout.read(): - openrc = True - rc = 'rc-' - network = 'network' -else: - openrc = False - rc = '' - network = 'netif' - - def card_online(netcard): lan = Popen('ifconfig ' + netcard, shell=True, stdout=PIPE, universal_newlines=True) @@ -129,19 +116,7 @@ def barpercent(sn): def network_service_state(): - if openrc is True: - status = Popen( - f'{rc}service {network} status', - shell=True, - stdout=PIPE, - universal_newlines=True - ) - if 'status: started' in status.stdout.read(): - return True - else: - return False - else: - return False + return False def networkdictionary(): @@ -247,39 +222,29 @@ def switch_default(nic): ).stdout.read() if 'status: active' in nic_info or 'status: associated' in nic_info: if 'inet ' in nic_info or 'inet6' in nic_info: - if openrc: - os.system(f'service dhcpcd.{card} restart') - else: - os.system(f'service dhclient restart {card}') + os.system(f'service dhclient restart {card}') break return def stopallnetwork(): - os.system(f'{rc}service {network} stop') + os.system('service netif stop') def startallnetwork(): - os.system(f'{rc}service {network} start') + os.system('service netif start') def stopnetworkcard(netcard): - if openrc is True: - os.system(f'ifconfig {netcard} down') - else: - os.system(f'service netif stop {netcard}') - switch_default(netcard) + os.system(f'service netif stop {netcard}') + switch_default(netcard) def startnetworkcard(netcard): - if openrc is True: - os.system(f'ifconfig {netcard} up') - os.system(f'{rc}service dhcpcd.{netcard} restart') - else: - os.system(f'service netif start {netcard}') - sleep(1) - os.system('service routing restart') - os.system(f'service dhclient start {netcard}') + os.system(f'service netif start {netcard}') + sleep(1) + os.system('service routing restart') + os.system(f'service dhclient start {netcard}') def wifiDisconnection(wificard): @@ -348,8 +313,4 @@ def wlan_status(card): def start_dhcp(wificard): - if openrc is True: - os.system(f'dhcpcd -x {wificard}') - os.system(f'dhcpcd {wificard}') - else: - os.system(f'dhclient {wificard}') + os.system(f'dhclient {wificard}') diff --git a/src/trayicon.py b/src/trayicon.py index 6e8da05..ecf718b 100755 --- a/src/trayicon.py +++ b/src/trayicon.py @@ -21,7 +21,6 @@ enableWifi, connectionStatus, networkdictionary, - openrc, delete_ssid_wpa_supplicant_config, wlan_status ) @@ -135,18 +134,16 @@ def nm_menu(self): self.menu.append(configure_item) self.menu.append(Gtk.SeparatorMenuItem()) wifinum += 1 - - if openrc is True: - if self.cardinfo['service'] is False: - open_item = Gtk.MenuItem("Enable Networking") - open_item.connect("activate", self.openNetwork) - self.menu.append(open_item) - else: - close_item = Gtk.MenuItem("Disable Networking") - close_item.connect("activate", self.closeNetwork) - self.menu.append(close_item) + if self.cardinfo['service'] is False: + open_item = Gtk.MenuItem("Enable Networking") + open_item.connect("activate", self.openNetwork) + self.menu.append(open_item) else: - print('service netif status not supported') + close_item = Gtk.MenuItem("Disable Networking") + close_item.connect("activate", self.closeNetwork) + self.menu.append(close_item) + # else: + # print('service netif status not supported') close_manager = Gtk.MenuItem("Close Network Manager") close_manager.connect("activate", self.stop_manager) self.menu.append(close_manager) From f9479c3c510ea8168f9e796b56c4fcdf0021fa88 Mon Sep 17 00:00:00 2001 From: ericbsd Date: Mon, 21 Feb 2022 16:29:24 -0400 Subject: [PATCH 17/24] Added better IPV4 UI integration --- src/netcardmgr.py | 175 ++++++++++++++++++++++++++++------------------ 1 file changed, 106 insertions(+), 69 deletions(-) diff --git a/src/netcardmgr.py b/src/netcardmgr.py index 0a1d6f1..be3214d 100755 --- a/src/netcardmgr.py +++ b/src/netcardmgr.py @@ -3,10 +3,10 @@ import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk -from subprocess import Popen, PIPE +from subprocess import Popen, PIPE, check_output import os import re -import subprocess +# import subprocess from time import sleep ncard = 'ifconfig -l' @@ -61,6 +61,22 @@ class netCardConfigWindow(Gtk.Window): + def edit_ipv4_setting(self, widget, value): + if value == "DHCP": + self.ipInputAddressEntry.set_sensitive(False) + self.ipInputMaskEntry.set_sensitive(False) + self.ipInputGatewayEntry.set_sensitive(False) + self.dnsEntry.set_sensitive(False) + self.searchEntry.set_sensitive(False) + self.saveButton.set_sensitive(False) + else: + self.ipInputAddressEntry.set_sensitive(True) + self.ipInputMaskEntry.set_sensitive(True) + self.ipInputGatewayEntry.set_sensitive(True) + self.dnsEntry.set_sensitive(True) + self.searchEntry.set_sensitive(True) + self.saveButton.set_sensitive(True) + def __init__(self, defaultactiveint): # Build Default Window Gtk.Window.__init__(self, title="Network Interface Configuration") @@ -102,15 +118,17 @@ def __init__(self, defaultactiveint): interfaceBox.pack_end(interfaceComboBox, True, True, 0) # Add radio button to toggle DHCP or not - radioButton1 = Gtk.RadioButton.new_with_label(None, "DHCP") - radioButton1.set_margin_top(15) - radioButton2 = Gtk.RadioButton.new_with_label_from_widget(radioButton1, "Manual") - radioButton2.set_margin_top(15) + rb_dhcp4 = Gtk.RadioButton.new_with_label(None, "DHCP") + rb_dhcp4.set_margin_top(15) + rb_dhcp4.connect("toggled", self.edit_ipv4_setting, "DHCP") + rb_manual4 = Gtk.RadioButton.new_with_label_from_widget(rb_dhcp4, "Manual") + rb_manual4.set_margin_top(15) + rb_manual4.connect("toggled", self.edit_ipv4_setting, "Manual") if currentSettings["Address Assignment Method"] == "DHCP": - radioButton1.set_active(True) + rb_dhcp4.set_active(True) else: - radioButton2.set_active(True) - radioButton2.join_group(radioButton1) + rb_manual4.set_active(True) + rb_manual4.join_group(rb_dhcp4) radioButtonLabel = Gtk.Label(label="IPv4 Method:") radioButtonLabel.set_margin_top(15) @@ -119,8 +137,8 @@ def __init__(self, defaultactiveint): radioBox = Gtk.Box(orientation=0, spacing=50) radioBox.set_homogeneous(False) radioBox.pack_start(radioButtonLabel, False, False, 0) - radioBox.pack_start(radioButton1, True, False, 0) - radioBox.pack_end(radioButton2, True, True, 0) + radioBox.pack_start(rb_dhcp4, True, False, 0) + radioBox.pack_end(rb_manual4, True, True, 0) # Add Manual Address Field ipInputAddressLabel = Gtk.Label(label="Address") @@ -132,16 +150,16 @@ def __init__(self, defaultactiveint): ipInputGatewayLabel = Gtk.Label(label="Gateway") ipInputGatewayLabel.set_margin_top(15) - ipInputAddressEntry = Gtk.Entry() - ipInputAddressEntry.set_margin_start(15) - ipInputAddressEntry.set_text(currentSettings["Interface IP"]) + self.ipInputAddressEntry = Gtk.Entry() + self.ipInputAddressEntry.set_margin_start(15) + self.ipInputAddressEntry.set_text(currentSettings["Interface IP"]) - ipInputMaskEntry = Gtk.Entry() - ipInputMaskEntry.set_text(currentSettings["Interface Subnet Mask"]) + self.ipInputMaskEntry = Gtk.Entry() + self.ipInputMaskEntry.set_text(currentSettings["Interface Subnet Mask"]) - ipInputGatewayEntry = Gtk.Entry() - ipInputGatewayEntry.set_margin_end(15) - ipInputGatewayEntry.set_text(currentSettings["Default Gateway"]) + self.ipInputGatewayEntry = Gtk.Entry() + self.ipInputGatewayEntry.set_margin_end(15) + self.ipInputGatewayEntry.set_text(currentSettings["Default Gateway"]) ipInputBox = Gtk.Box(orientation=0, spacing=0) ipInputBox.set_homogeneous(True) @@ -150,9 +168,9 @@ def __init__(self, defaultactiveint): ipInputBox.pack_start(ipInputGatewayLabel, False, False, 0) ipEntryBox = Gtk.Box(orientation=0, spacing=30) - ipEntryBox.pack_start(ipInputAddressEntry, False, False, 0) - ipEntryBox.pack_start(ipInputMaskEntry, False, False, 0) - ipEntryBox.pack_start(ipInputGatewayEntry, False, False, 0) + ipEntryBox.pack_start(self.ipInputAddressEntry, False, False, 0) + ipEntryBox.pack_start(self.ipInputMaskEntry, False, False, 0) + ipEntryBox.pack_start(self.ipInputGatewayEntry, False, False, 0) # Add DNS Server Settings dnsLabel = Gtk.Label(label="DNS Servers: ") @@ -160,8 +178,8 @@ def __init__(self, defaultactiveint): dnsLabel.set_margin_end(58) dnsLabel.set_margin_start(30) - dnsEntry = Gtk.Entry() - dnsEntry.set_margin_end(30) + self.dnsEntry = Gtk.Entry() + self.dnsEntry.set_margin_end(30) DNSList = [(key, value) for key, value in currentSettings.items() if key.startswith("DNS Server")] print(DNSList) i = 0 @@ -171,11 +189,11 @@ def __init__(self, defaultactiveint): if i + 1 < len(DNSList): DNSString = DNSString + "," i = i + 1 - dnsEntry.set_text(DNSString) + self.dnsEntry.set_text(DNSString) dnsEntryBox = Gtk.Box(orientation=0, spacing=0) dnsEntryBox.pack_start(dnsLabel, False, False, 0) - dnsEntryBox.pack_end(dnsEntry, True, True, 0) + dnsEntryBox.pack_end(self.dnsEntry, True, True, 0) # Add Search Domain Settings @@ -184,16 +202,21 @@ def __init__(self, defaultactiveint): searchLabel.set_margin_end(30) searchLabel.set_margin_start(30) - searchEntry = Gtk.Entry() - searchEntry.set_margin_top(21) - searchEntry.set_margin_end(30) - searchEntry.set_margin_bottom(30) - searchEntry.set_text(currentSettings["Search Domain"]) + self.searchEntry = Gtk.Entry() + self.searchEntry.set_margin_top(21) + self.searchEntry.set_margin_end(30) + self.searchEntry.set_margin_bottom(30) + self.searchEntry.set_text(currentSettings["Search Domain"]) searchBox = Gtk.Box(orientation=0, spacing=0) searchBox.pack_start(searchLabel, False, False, 0) - searchBox.pack_end(searchEntry, True, True, 0) - + searchBox.pack_end(self.searchEntry, True, True, 0) + if currentSettings["Address Assignment Method"] == "DHCP": + self.ipInputAddressEntry.set_sensitive(False) + self.ipInputMaskEntry.set_sensitive(False) + self.ipInputGatewayEntry.set_sensitive(False) + self.dnsEntry.set_sensitive(False) + self.searchEntry.set_sensitive(False) # Build the grid, which will handle the physical layout of the UI elements. gridOne = Gtk.Grid() gridOne.set_column_homogeneous(True) @@ -242,11 +265,11 @@ def __init__(self, defaultactiveint): interfaceBox6.pack_end(interfaceComboBox6, True, True, 0) # Add radio button to toggle DHCP or not - radioButton1V6 = Gtk.RadioButton.new_with_label(None, "SLAAC") - radioButton1V6.set_margin_top(15) - radioButton2V6 = Gtk.RadioButton.new_with_label_from_widget(radioButton1V6, "Manual") - radioButton2V6.set_margin_top(15) - radioButton2V6.join_group(radioButton1V6) + rb_slaac6 = Gtk.RadioButton.new_with_label(None, "SLAAC") + rb_slaac6.set_margin_top(15) + rb_manual6 = Gtk.RadioButton.new_with_label_from_widget(rb_slaac6, "Manual") + rb_manual6.set_margin_top(15) + rb_manual6.join_group(rb_slaac6) radioButtonLabel6 = Gtk.Label(label="IPv4 Method:") radioButtonLabel6.set_margin_top(15) @@ -255,8 +278,8 @@ def __init__(self, defaultactiveint): radioBox6 = Gtk.Box(orientation=0, spacing=50) radioBox6.set_homogeneous(False) radioBox6.pack_start(radioButtonLabel6, False, False, 0) - radioBox6.pack_start(radioButton1V6, True, False, 0) - radioBox6.pack_end(radioButton2V6, True, True, 0) + radioBox6.pack_start(rb_slaac6, True, False, 0) + radioBox6.pack_end(rb_manual6, True, True, 0) # Add Manual Address Field ipInputAddressLabel6 = Gtk.Label(label="Address") @@ -268,11 +291,11 @@ def __init__(self, defaultactiveint): ipInputGatewayLabel6 = Gtk.Label(label="Gateway") ipInputGatewayLabel6.set_margin_top(15) - ipInputAddressEntry6 = Gtk.Entry() - ipInputAddressEntry6.set_margin_start(15) - ipInputMaskEntry6 = Gtk.Entry() - ipInputGatewayEntry6 = Gtk.Entry() - ipInputGatewayEntry6.set_margin_end(15) + self.ipInputAddressEntry6 = Gtk.Entry() + self.ipInputAddressEntry6.set_margin_start(15) + self.ipInputMaskEntry6 = Gtk.Entry() + self.ipInputGatewayEntry6 = Gtk.Entry() + self.ipInputGatewayEntry6.set_margin_end(15) ipInputBox6 = Gtk.Box(orientation=0, spacing=0) ipInputBox6.set_homogeneous(True) @@ -281,9 +304,9 @@ def __init__(self, defaultactiveint): ipInputBox6.pack_start(ipInputGatewayLabel6, False, False, 0) ipEntryBox6 = Gtk.Box(orientation=0, spacing=30) - ipEntryBox6.pack_start(ipInputAddressEntry6, False, False, 0) - ipEntryBox6.pack_start(ipInputMaskEntry6, False, False, 0) - ipEntryBox6.pack_start(ipInputGatewayEntry6, False, False, 0) + ipEntryBox6.pack_start(self.ipInputAddressEntry6, False, False, 0) + ipEntryBox6.pack_start(self.ipInputMaskEntry6, False, False, 0) + ipEntryBox6.pack_start(self.ipInputGatewayEntry6, False, False, 0) # Add DNS Server Settings dnsLabel6 = Gtk.Label(label="DNS Servers: ") @@ -291,12 +314,12 @@ def __init__(self, defaultactiveint): dnsLabel6.set_margin_end(58) dnsLabel6.set_margin_start(30) - dnsEntry6 = Gtk.Entry() - dnsEntry6.set_margin_end(30) + self.dnsEntry6 = Gtk.Entry() + self.dnsEntry6.set_margin_end(30) dnsEntryBox6 = Gtk.Box(orientation=0, spacing=0) dnsEntryBox6.pack_start(dnsLabel6, False, False, 0) - dnsEntryBox6.pack_end(dnsEntry6, True, True, 0) + dnsEntryBox6.pack_end(self.dnsEntry6, True, True, 0) # Add Search Domain Settings @@ -305,15 +328,20 @@ def __init__(self, defaultactiveint): searchLabel6.set_margin_end(30) searchLabel6.set_margin_start(30) - searchEntry6 = Gtk.Entry() - searchEntry6.set_margin_top(21) - searchEntry6.set_margin_end(30) - searchEntry6.set_margin_bottom(30) + self.searchEntry6 = Gtk.Entry() + self.searchEntry6.set_margin_top(21) + self.searchEntry6.set_margin_end(30) + self.searchEntry6.set_margin_bottom(30) searchBox6 = Gtk.Box(orientation=0, spacing=0) searchBox6.pack_start(searchLabel6, False, False, 0) - searchBox6.pack_end(searchEntry6, True, True, 0) + searchBox6.pack_end(self.searchEntry6, True, True, 0) + self.ipInputAddressEntry6.set_sensitive(False) + self.ipInputMaskEntry6.set_sensitive(False) + self.ipInputGatewayEntry6.set_sensitive(False) + self.dnsEntry6.set_sensitive(False) + self.searchEntry6.set_sensitive(False) # Build the grid, which will handle the physical layout of the UI elements. gridOne6 = Gtk.Grid() gridOne6.set_column_homogeneous(True) @@ -338,15 +366,17 @@ def __init__(self, defaultactiveint): # Build Save & Cancel Buttons - saveButton = Gtk.Button(label="Save...") - saveButton.set_margin_bottom(10) - saveButton.set_margin_start(10) - saveButton.connect("clicked", self.commit_pending_changes) + self.saveButton = Gtk.Button(label="Save...") + self.saveButton.set_margin_bottom(10) + self.saveButton.set_margin_start(10) + self.saveButton.connect("clicked", self.commit_pending_changes) + if currentSettings["Address Assignment Method"] == "DHCP": + self.saveButton.set_sensitive(False) cancelButton = Gtk.Button(label="Cancel...") cancelButton.set_margin_bottom(10) cancelButton.connect("clicked", self.discard_pending_changes) buttonsWindow = Gtk.Box(orientation=0, spacing=10) - buttonsWindow.pack_start(saveButton, False, False, 0) + buttonsWindow.pack_start(self.saveButton, False, False, 0) buttonsWindow.pack_start(cancelButton, False, False, 0) # Apply Tab 1 content and formatting to the notebook @@ -397,9 +427,9 @@ def cbox_config_refresh(self, widget): self.get_current_interface_settings(refreshedInterfaceName) self.display_current_interface_settings(widget) - def get_current_interface_settings(self, active_int): + def get_current_interface_settings(self, active_nic): # Need to accurately determine if a wlanN interface is using DHCP - aInt = str(active_int) + aInt = str(active_nic) DHCPStatus = os.path.exists(f"/var/db/dhclient.leases.{aInt}") print(f"dhcpstatus return value = {DHCPStatus}") @@ -417,7 +447,8 @@ def get_current_interface_settings(self, active_int): print(f"DHCPStatusOutput = {DHCPStatusOutput}") ifconfigaInt = f"ifconfig -f inet:dotted {aInt}" - ifconfigaIntOutput = subprocess.check_output(ifconfigaInt.split(" ")) + ifconfigaIntOutput = check_output(ifconfigaInt.split(" ")) + aIntIP = re.findall(r'inet [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+', str(ifconfigaIntOutput))[0] aIntIPStrip = str(aIntIP).replace("inet ", "") aIntIPStrip = str(aIntIPStrip).replace("'", "") @@ -455,11 +486,16 @@ def get_current_interface_settings(self, active_int): aIntGatewayStrip = str(aIntGatewayStrip).replace("]", "") aIntGatewayStrip = str(aIntGatewayStrip).replace(";", "") - aIntDHCP = f"resolvconf -l {aInt}.dhcp" - aIntDHCPResults = subprocess.check_output(aIntDHCP.split(" ")) - DNSMatch = re.findall(r'nameserver [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+', str(aIntDHCPResults)) + # aIntDHCP = f"resolvconf -l {aInt}" + # aIntDHCPResults = subprocess.check_output(aIntDHCP.split(" ")) + # aIntDHCPResults = subprocess.run(aIntDHCP.split(" "), + # capture_output=True, + # text=True) + # DNSMatch = re.findall(r'nameserver [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+', str(aIntDHCPResults)) + DefaultDNSServers = open('/etc/resolv.conf').read() + DNSMatch = re.findall(r'nameserver [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+', str(DefaultDNSServers)) - SearchDomainMatch = re.findall('search [a-zA-Z.]*', str(aIntDHCPResults)) + SearchDomainMatch = re.findall('search [a-zA-Z.]*', str(DefaultDNSServers)) if len(SearchDomainMatch) < 1: RCConfDomainSearch = open('/etc/resolv.conf', 'r').read() SearchDomainMatch = re.findall('domain (.*)', RCConfDomainSearch) @@ -487,7 +523,7 @@ def get_current_interface_settings(self, active_int): SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("]", "") # currentSettings = {} - currentSettings["Active Interface"] = active_int + currentSettings["Active Interface"] = active_nic currentSettings["Address Assignment Method"] = DHCPStatusOutput currentSettings["Interface IP"] = aIntIPStrip currentSettings["Interface Subnet Mask"] = aIntMaskStrip @@ -511,6 +547,7 @@ def commit_pending_changes(self, widget): def discard_pending_changes(self, widget): print("discard_pending_changes_goes_here") + self.destroy() def openNetCardConfigwindow(default_int): From b3ed03b54d3b5eab8719746a414c167e7fc503fc Mon Sep 17 00:00:00 2001 From: ericbsd Date: Mon, 21 Feb 2022 16:34:38 -0400 Subject: [PATCH 18/24] remove unused code in netcardmgr.py --- src/netcardmgr.py | 42 ------------------------------------------ 1 file changed, 42 deletions(-) diff --git a/src/netcardmgr.py b/src/netcardmgr.py index be3214d..5c37c80 100755 --- a/src/netcardmgr.py +++ b/src/netcardmgr.py @@ -6,56 +6,14 @@ from subprocess import Popen, PIPE, check_output import os import re -# import subprocess from time import sleep -ncard = 'ifconfig -l' -nics = Popen(ncard, shell=True, stdout=PIPE, close_fds=True, - universal_newlines=True) -netcard = nics.stdout.readlines()[0].rstrip() -wifis = 'sysctl -in net.wlan.devices' -wifinics = Popen(wifis, shell=True, stdout=PIPE, close_fds=True, - universal_newlines=True) -wifiscard = wifinics.stdout.readlines()[0].rstrip() rcconf = open('/etc/rc.conf', 'r').read() if os.path.exists('/etc/rc.conf.local'): rcconflocal = open('/etc/rc.conf.local', 'r').read() else: rcconflocal = "None" -notnics = [ - "enc", - "lo", - "fwe", - "fwip", - "tap", - "plip", - "pfsync", - "pflog", - "ipfw", - "tun", - "sl", - "faith", - "ppp", - "bridge", - "ixautomation", - "vm-ixautomation", - "wg" -] - -cmd = "kenv | grep rc_system" -rc_system = Popen(cmd, shell=True, stdout=PIPE, universal_newlines=True) -if 'openrc' in rc_system.stdout.read(): - openrc = True - rc = 'rc-' - network = 'network' -else: - openrc = False - rc = '' - network = 'netif' - -restart_network = f'{rc}service {network} restart' - currentSettings = {} From 47d90280a9b90b09222afaa3cd00a871a166ebbb Mon Sep 17 00:00:00 2001 From: ericbsd Date: Wed, 23 Feb 2022 07:25:20 -0400 Subject: [PATCH 19/24] Added ipv6 lock entry on SLAAC --- src/netcardmgr.py | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/netcardmgr.py b/src/netcardmgr.py index 5c37c80..834b19e 100755 --- a/src/netcardmgr.py +++ b/src/netcardmgr.py @@ -35,6 +35,22 @@ def edit_ipv4_setting(self, widget, value): self.searchEntry.set_sensitive(True) self.saveButton.set_sensitive(True) + def edit_ipv6_setting(self, widget, value): + if value == "SLAAC": + self.ipInputAddressEntry6.set_sensitive(False) + self.ipInputMaskEntry6.set_sensitive(False) + self.ipInputGatewayEntry6.set_sensitive(False) + self.dnsEntry6.set_sensitive(False) + self.searchEntry6.set_sensitive(False) + self.saveButton.set_sensitive(False) + else: + self.ipInputAddressEntry6.set_sensitive(True) + self.ipInputMaskEntry6.set_sensitive(True) + self.ipInputGatewayEntry6.set_sensitive(True) + self.dnsEntry6.set_sensitive(True) + self.searchEntry6.set_sensitive(True) + self.saveButton.set_sensitive(True) + def __init__(self, defaultactiveint): # Build Default Window Gtk.Window.__init__(self, title="Network Interface Configuration") @@ -225,9 +241,11 @@ def __init__(self, defaultactiveint): # Add radio button to toggle DHCP or not rb_slaac6 = Gtk.RadioButton.new_with_label(None, "SLAAC") rb_slaac6.set_margin_top(15) + rb_slaac6.connect("toggled", self.edit_ipv6_setting, "SLAAC") rb_manual6 = Gtk.RadioButton.new_with_label_from_widget(rb_slaac6, "Manual") rb_manual6.set_margin_top(15) rb_manual6.join_group(rb_slaac6) + rb_manual6.connect("toggled", self.edit_ipv6_setting, "Manual") radioButtonLabel6 = Gtk.Label(label="IPv4 Method:") radioButtonLabel6.set_margin_top(15) @@ -344,7 +362,6 @@ def __init__(self, defaultactiveint): # Apply Tab 2 content and formatting to the notebook nb.append_page(gridOne6) nb.set_tab_label_text(gridOne6, "IPv6 Settings") - # Put all the widgets together into one window mainBox = Gtk.Box(orientation=1, spacing=0) mainBox.pack_start(nb, False, False, 0) @@ -383,7 +400,7 @@ def cbox_config_refresh(self, widget): print(f"Refreshing settings to match current settings on {refreshedInterface}. " f"Interface name is {refreshedInterfaceName}") self.get_current_interface_settings(refreshedInterfaceName) - self.display_current_interface_settings(widget) + # self.display_current_interface_settings(widget) def get_current_interface_settings(self, active_nic): # Need to accurately determine if a wlanN interface is using DHCP From 1f21602c74fc39b176b4062b1efb037650e031f2 Mon Sep 17 00:00:00 2001 From: ericbsd Date: Sat, 11 Mar 2023 11:43:19 -0400 Subject: [PATCH 20/24] adding some UI and backend improvement --- src/netcardmgr.py | 117 ++++++++++++++++++++++++++-------------------- 1 file changed, 67 insertions(+), 50 deletions(-) diff --git a/src/netcardmgr.py b/src/netcardmgr.py index 834b19e..2ece7e0 100755 --- a/src/netcardmgr.py +++ b/src/netcardmgr.py @@ -24,14 +24,16 @@ def edit_ipv4_setting(self, widget, value): self.ipInputAddressEntry.set_sensitive(False) self.ipInputMaskEntry.set_sensitive(False) self.ipInputGatewayEntry.set_sensitive(False) - self.dnsEntry.set_sensitive(False) + self.prymary_dnsEntry.set_sensitive(False) + self.secondary_dnsEntry.set_sensitive(False) self.searchEntry.set_sensitive(False) self.saveButton.set_sensitive(False) else: self.ipInputAddressEntry.set_sensitive(True) self.ipInputMaskEntry.set_sensitive(True) self.ipInputGatewayEntry.set_sensitive(True) - self.dnsEntry.set_sensitive(True) + self.prymary_dnsEntry.set_sensitive(True) + self.secondary_dnsEntry.set_sensitive(True) self.searchEntry.set_sensitive(True) self.saveButton.set_sensitive(True) @@ -40,14 +42,14 @@ def edit_ipv6_setting(self, widget, value): self.ipInputAddressEntry6.set_sensitive(False) self.ipInputMaskEntry6.set_sensitive(False) self.ipInputGatewayEntry6.set_sensitive(False) - self.dnsEntry6.set_sensitive(False) + self.prymary_dnsEntry6.set_sensitive(False) self.searchEntry6.set_sensitive(False) self.saveButton.set_sensitive(False) else: self.ipInputAddressEntry6.set_sensitive(True) self.ipInputMaskEntry6.set_sensitive(True) self.ipInputGatewayEntry6.set_sensitive(True) - self.dnsEntry6.set_sensitive(True) + self.prymary_dnsEntry6.set_sensitive(True) self.searchEntry6.set_sensitive(True) self.saveButton.set_sensitive(True) @@ -147,30 +149,35 @@ def __init__(self, defaultactiveint): ipEntryBox.pack_start(self.ipInputGatewayEntry, False, False, 0) # Add DNS Server Settings - dnsLabel = Gtk.Label(label="DNS Servers: ") - dnsLabel.set_margin_top(15) - dnsLabel.set_margin_end(58) - dnsLabel.set_margin_start(30) - - self.dnsEntry = Gtk.Entry() - self.dnsEntry.set_margin_end(30) - DNSList = [(key, value) for key, value in currentSettings.items() if key.startswith("DNS Server")] - print(DNSList) - i = 0 - DNSString = "" - while i < len(DNSList): - DNSString = DNSString + DNSList[i][1] - if i + 1 < len(DNSList): - DNSString = DNSString + "," - i = i + 1 - self.dnsEntry.set_text(DNSString) - - dnsEntryBox = Gtk.Box(orientation=0, spacing=0) - dnsEntryBox.pack_start(dnsLabel, False, False, 0) - dnsEntryBox.pack_end(self.dnsEntry, True, True, 0) + prymary_dns_Label = Gtk.Label(label="Primary DNS Servers: ") + prymary_dns_Label.set_margin_top(15) + prymary_dns_Label.set_margin_end(58) + prymary_dns_Label.set_margin_start(30) - # Add Search Domain Settings + secondary_dns_Label = Gtk.Label(label="Secondary DNS Servers: ") + secondary_dns_Label.set_margin_top(15) + secondary_dns_Label.set_margin_end(58) + secondary_dns_Label.set_margin_start(30) + + self.prymary_dnsEntry = Gtk.Entry() + self.prymary_dnsEntry.set_margin_end(30) + self.prymary_dnsEntry.set_text(currentSettings["DNS Server 1"]) + + self.secondary_dnsEntry = Gtk.Entry() + self.secondary_dnsEntry.set_margin_end(30) + self.secondary_dnsEntry.set_text(currentSettings["DNS Server 2"]) + + dnsEntryBox1 = Gtk.Box(orientation=0, spacing=0) + dnsEntryBox1.pack_start(prymary_dns_Label, False, False, 0) + + dnsEntryBox1.pack_end(self.prymary_dnsEntry, True, True, 0) + + dnsEntryBox2 = Gtk.Box(orientation=0, spacing=0) + dnsEntryBox2.pack_start(secondary_dns_Label, False, False, 0) + dnsEntryBox2.pack_end(self.secondary_dnsEntry, True, True, 0) + + # Add Search Domain Settings searchLabel = Gtk.Label(label="Search domains: ") searchLabel.set_margin_top(15) searchLabel.set_margin_end(30) @@ -189,7 +196,8 @@ def __init__(self, defaultactiveint): self.ipInputAddressEntry.set_sensitive(False) self.ipInputMaskEntry.set_sensitive(False) self.ipInputGatewayEntry.set_sensitive(False) - self.dnsEntry.set_sensitive(False) + self.prymary_dnsEntry.set_sensitive(False) + self.secondary_dnsEntry.set_sensitive(False) self.searchEntry.set_sensitive(False) # Build the grid, which will handle the physical layout of the UI elements. gridOne = Gtk.Grid() @@ -201,8 +209,9 @@ def __init__(self, defaultactiveint): gridOne.attach(radioBox, 0, 1, 4, 1) gridOne.attach(ipInputBox, 0, 2, 4, 1) gridOne.attach(ipEntryBox, 0, 3, 4, 1) - gridOne.attach(dnsEntryBox, 0, 4, 4, 1) - gridOne.attach(searchBox, 0, 5, 4, 1) + gridOne.attach(dnsEntryBox1, 0, 4, 4, 1) + gridOne.attach(dnsEntryBox2, 0, 5, 4, 1) + gridOne.attach(searchBox, 0, 6, 4, 1) # Build Tab 2 Content @@ -285,17 +294,22 @@ def __init__(self, defaultactiveint): ipEntryBox6.pack_start(self.ipInputGatewayEntry6, False, False, 0) # Add DNS Server Settings - dnsLabel6 = Gtk.Label(label="DNS Servers: ") - dnsLabel6.set_margin_top(15) - dnsLabel6.set_margin_end(58) - dnsLabel6.set_margin_start(30) + prymary_dns_Label6 = Gtk.Label(label="Primary DNS Servers: ") + prymary_dns_Label6.set_margin_top(15) + prymary_dns_Label6.set_margin_end(58) + prymary_dns_Label6.set_margin_start(30) + + secondary_dns_Label6 = Gtk.Label(label="Secondary DNS Servers: ") + secondary_dns_Label6.set_margin_top(15) + secondary_dns_Label6.set_margin_end(58) + secondary_dns_Label6.set_margin_start(30) - self.dnsEntry6 = Gtk.Entry() - self.dnsEntry6.set_margin_end(30) + self.prymary_dnsEntry6 = Gtk.Entry() + self.prymary_dnsEntry6.set_margin_end(30) dnsEntryBox6 = Gtk.Box(orientation=0, spacing=0) - dnsEntryBox6.pack_start(dnsLabel6, False, False, 0) - dnsEntryBox6.pack_end(self.dnsEntry6, True, True, 0) + dnsEntryBox6.pack_start(prymary_dns_Label6, False, False, 0) + dnsEntryBox6.pack_end(self.prymary_dnsEntry6, True, True, 0) # Add Search Domain Settings @@ -316,7 +330,7 @@ def __init__(self, defaultactiveint): self.ipInputAddressEntry6.set_sensitive(False) self.ipInputMaskEntry6.set_sensitive(False) self.ipInputGatewayEntry6.set_sensitive(False) - self.dnsEntry6.set_sensitive(False) + self.prymary_dnsEntry6.set_sensitive(False) self.searchEntry6.set_sensitive(False) # Build the grid, which will handle the physical layout of the UI elements. gridOne6 = Gtk.Grid() @@ -330,6 +344,7 @@ def __init__(self, defaultactiveint): gridOne6.attach(ipEntryBox6, 0, 3, 4, 1) gridOne6.attach(dnsEntryBox6, 0, 4, 4, 1) gridOne6.attach(searchBox6, 0, 5, 4, 1) + gridOne6.set_sensitive(False) # Build Notebook @@ -339,16 +354,16 @@ def __init__(self, defaultactiveint): nb.set_margin_top(10) nb.set_margin_bottom(10) nb.set_tab_pos(2) - + # nb.set_sensitive(False) # Build Save & Cancel Buttons - self.saveButton = Gtk.Button(label="Save...") + self.saveButton = Gtk.Button(label="Save") self.saveButton.set_margin_bottom(10) self.saveButton.set_margin_start(10) self.saveButton.connect("clicked", self.commit_pending_changes) if currentSettings["Address Assignment Method"] == "DHCP": self.saveButton.set_sensitive(False) - cancelButton = Gtk.Button(label="Cancel...") + cancelButton = Gtk.Button(label="Cancel") cancelButton.set_margin_bottom(10) cancelButton.connect("clicked", self.discard_pending_changes) buttonsWindow = Gtk.Box(orientation=0, spacing=10) @@ -361,11 +376,11 @@ def __init__(self, defaultactiveint): # Apply Tab 2 content and formatting to the notebook nb.append_page(gridOne6) - nb.set_tab_label_text(gridOne6, "IPv6 Settings") + nb.set_tab_label_text(gridOne6, "IPv6 Settings WIP") # Put all the widgets together into one window mainBox = Gtk.Box(orientation=1, spacing=0) - mainBox.pack_start(nb, False, False, 0) - mainBox.pack_start(buttonsWindow, False, False, 0) + mainBox.pack_start(nb, True, True, 0) + mainBox.pack_end(buttonsWindow, False, False, 0) self.add(mainBox) # Run any functions that need to execute once at window creation @@ -375,7 +390,8 @@ def __init__(self, defaultactiveint): def enumerate_nics(self): validnics = list() confnotnics = ["lo", "fwe", "fwip", "tap", "plip", "pfsync", "pflog", - "tun", "sl", "faith", "ppp", "bridge", "ixautomation"] + "tun", "sl", "faith", "ppp", "bridge", "ixautomation", + "wg"] confncard = 'ifconfig -l' confnics = Popen(confncard, shell=True, stdout=PIPE, close_fds=True, universal_newlines=True) confnetcard = confnics.stdout.readlines()[0].rstrip() @@ -390,7 +406,7 @@ def enumerate_nics(self): "It will not be added to the valid configurable nic list in the netCardConfigWindow.enumerate_nics method.") else: validnics.append(confnic) - return(validnics) + return validnics # Used with the combo box to refresh the UI of tab 1 with active settings for the newly selected active interface. def cbox_config_refresh(self, widget): @@ -478,6 +494,7 @@ def get_current_interface_settings(self, active_nic): SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("'", "") SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("[", "") SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("]", "") + SearchDomainMatchStrip = SearchDomainMatchStrip.replace('search', '').strip() else: RRConfGatewaySearch = open('/etc/rc.conf', 'r').read() RRConfGatewayResults = re.findall(r'defaultrouter="[0-9]+\.[0-9]+\.[0-9]+\.[0-9]"', RRConfGatewaySearch) @@ -496,6 +513,7 @@ def get_current_interface_settings(self, active_nic): SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("'", "") SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("[", "") SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("]", "") + SearchDomainMatchStrip = SearchDomainMatchStrip.replace('search', '').strip() # currentSettings = {} currentSettings["Active Interface"] = active_nic @@ -506,10 +524,9 @@ def get_current_interface_settings(self, active_nic): currentSettings["Default Gateway"] = aIntGatewayStrip # [currentSettings.append(str(DNSServer).replace("nameserver ", "")) for DNSServer in DNSMatch] currentSettings["Search Domain"] = SearchDomainMatchStrip - i = 1 - while i <= len(DNSMatch): - currentSettings[f"DNS Server {i}"] = str(DNSMatch[(i - 1)]).replace("nameserver ", "") - i = i + 1 + + for num in range(len(DNSMatch)): + currentSettings[f"DNS Server {num + 1}"] = str(DNSMatch[(num)]).replace("nameserver", "").strip() print("Current settings are below:") print(f"{currentSettings}") From 3244db460290696bad62629a334baa63c0e6637b Mon Sep 17 00:00:00 2001 From: ericbsd Date: Sat, 24 Jun 2023 07:26:55 -0300 Subject: [PATCH 21/24] Adding functionality to configuration static IP and DNS --- LICENSE | 2 +- setup.py | 3 +- src/net_api.py | 43 ++---- src/netcardmgr.py | 385 +++++++++++++++++++++++----------------------- 4 files changed, 207 insertions(+), 226 deletions(-) diff --git a/LICENSE b/LICENSE index c936cde..184fdaf 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2014, GhostBSD +Copyright (c) 2012-2023, GhostBSD All rights reserved. Redistribution and use in source and binary forms, with or without modification, diff --git a/setup.py b/setup.py index 0776145..1599677 100755 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ from setuptools import setup from subprocess import run -__VERSION__ = '6.2' +__VERSION__ = '6.3' PROGRAM_VERSION = __VERSION__ prefix = '/usr/local' if system() == 'FreeBSD' else sys.prefix @@ -15,6 +15,7 @@ # compiling translations os.system("sh compile_translations.sh") + def datafilelist(installbase, sourcebase): datafileList = [] for root, subFolders, files in os.walk(sourcebase): diff --git a/src/net_api.py b/src/net_api.py index e07e096..bb1c5d1 100755 --- a/src/net_api.py +++ b/src/net_api.py @@ -1,32 +1,4 @@ #!/usr/bin/env python3 -""" -Copyright (c) 2014-2019, GhostBSD. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - -1. Redistribution's of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -2. Redistribution's in binary form must reproduce the above - copyright notice,this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING, -BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. -""" from subprocess import Popen, PIPE, run from sys import path @@ -92,7 +64,7 @@ def nics_list(): notnics_regex = r"(enc|lo|fwe|fwip|tap|plip|pfsync|pflog|ipfw|tun|sl|" \ r"faith|ppp|bridge|wg)[0-9]+(\s*)|vm-[a-z]+(\s*)" nics = Popen( - 'ifconfig -l ether', + 'ifconfig -l', shell=True, stdout=PIPE, universal_newlines=True @@ -240,6 +212,19 @@ def stopnetworkcard(netcard): switch_default(netcard) +def restart_dhcp_network(netcard): + os.system(f'service netif restart {netcard}') + sleep(1) + # os.system('service routing restart') + # os.system(f'service dhclient restart {netcard}') + + +def start_static_network(netcard, inet, netmask): + os.system(f'ifconfig {netcard} inet {inet} netmask {netmask}') + sleep(1) + os.system('service routing restart') + + def startnetworkcard(netcard): os.system(f'service netif start {netcard}') sleep(1) diff --git a/src/netcardmgr.py b/src/netcardmgr.py index 2ece7e0..1ced5d4 100755 --- a/src/netcardmgr.py +++ b/src/netcardmgr.py @@ -3,39 +3,46 @@ import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk -from subprocess import Popen, PIPE, check_output +from subprocess import check_output, run import os import re -from time import sleep - +from net_api import ( + start_static_network, + nics_list, + defaultcard, + restart_dhcp_network +) rcconf = open('/etc/rc.conf', 'r').read() if os.path.exists('/etc/rc.conf.local'): rcconflocal = open('/etc/rc.conf.local', 'r').read() else: rcconflocal = "None" +global currentSettings currentSettings = {} class netCardConfigWindow(Gtk.Window): - def edit_ipv4_setting(self, widget, value): - if value == "DHCP": - self.ipInputAddressEntry.set_sensitive(False) - self.ipInputMaskEntry.set_sensitive(False) - self.ipInputGatewayEntry.set_sensitive(False) - self.prymary_dnsEntry.set_sensitive(False) - self.secondary_dnsEntry.set_sensitive(False) - self.searchEntry.set_sensitive(False) - self.saveButton.set_sensitive(False) - else: - self.ipInputAddressEntry.set_sensitive(True) - self.ipInputMaskEntry.set_sensitive(True) - self.ipInputGatewayEntry.set_sensitive(True) - self.prymary_dnsEntry.set_sensitive(True) - self.secondary_dnsEntry.set_sensitive(True) - self.searchEntry.set_sensitive(True) - self.saveButton.set_sensitive(True) + def edit_ipv4_setting(self, widget): + if widget.get_active(): + self.method = widget.get_label() + if self.method == "DHCP": + self.ipInputAddressEntry.set_sensitive(False) + self.ipInputMaskEntry.set_sensitive(False) + self.ipInputGatewayEntry.set_sensitive(False) + self.prymary_dnsEntry.set_sensitive(False) + self.secondary_dnsEntry.set_sensitive(False) + else: + self.ipInputAddressEntry.set_sensitive(True) + self.ipInputMaskEntry.set_sensitive(True) + self.ipInputGatewayEntry.set_sensitive(True) + self.prymary_dnsEntry.set_sensitive(True) + self.secondary_dnsEntry.set_sensitive(True) + if self.method == currentSettings["Assignment Method"]: + self.saveButton.set_sensitive(False) + else: + self.saveButton.set_sensitive(True) def edit_ipv6_setting(self, widget, value): if value == "SLAAC": @@ -53,11 +60,12 @@ def edit_ipv6_setting(self, widget, value): self.searchEntry6.set_sensitive(True) self.saveButton.set_sensitive(True) - def __init__(self, defaultactiveint): + def __init__(self, selected_nic=None): # Build Default Window Gtk.Window.__init__(self, title="Network Interface Configuration") self.set_default_size(475, 400) - + self.NICS = nics_list() + DEFAULT_NIC = selected_nic if selected_nic else defaultcard() # Build Tab 1 Content # Interface Drop Down Combo Box @@ -69,19 +77,18 @@ def __init__(self, defaultactiveint): # Add interfaces to a ListStore store = Gtk.ListStore(str) - validinterfaces = self.enumerate_nics() - for validinterface in validinterfaces: - store.append([validinterface]) - # Build the UI aspects of the ComboBox, passing the interface clicked in the trayicon - # as the interface that needs to be the active one when the combo box is drawn - activeComboBoxObjectIndex = validinterfaces.index(f"{defaultactiveint}") + for nic in self.NICS: + store.append([nic]) + interfaceComboBox.set_model(store) interfaceComboBox.set_margin_top(15) interfaceComboBox.set_margin_end(30) - interfaceComboBox.set_active(activeComboBoxObjectIndex) - self.cbox_config_refresh(interfaceComboBox) - interfaceComboBox.connect("changed", self.cbox_config_refresh) + if DEFAULT_NIC: + active_index = self.NICS.index(f"{DEFAULT_NIC}") + interfaceComboBox.set_active(active_index) + self.get_current_interface_settings(DEFAULT_NIC) + interfaceComboBox.connect("changed", self.cbox_config_refresh, self.NICS) # Build Label to sit in front of the ComboBox labelOne = Gtk.Label(label="Interface:") @@ -94,17 +101,17 @@ def __init__(self, defaultactiveint): interfaceBox.pack_end(interfaceComboBox, True, True, 0) # Add radio button to toggle DHCP or not - rb_dhcp4 = Gtk.RadioButton.new_with_label(None, "DHCP") - rb_dhcp4.set_margin_top(15) - rb_dhcp4.connect("toggled", self.edit_ipv4_setting, "DHCP") - rb_manual4 = Gtk.RadioButton.new_with_label_from_widget(rb_dhcp4, "Manual") - rb_manual4.set_margin_top(15) - rb_manual4.connect("toggled", self.edit_ipv4_setting, "Manual") - if currentSettings["Address Assignment Method"] == "DHCP": - rb_dhcp4.set_active(True) + self.version = currentSettings["Assignment Method"] + self.rb_dhcp4 = Gtk.RadioButton.new_with_label(None, "DHCP") + self.rb_dhcp4.set_margin_top(15) + self.rb_manual4 = Gtk.RadioButton.new_with_label_from_widget( + self.rb_dhcp4, "Manual") + self.rb_manual4.set_margin_top(15) + if currentSettings["Assignment Method"] == "DHCP": + self.rb_dhcp4.set_active(True) else: - rb_manual4.set_active(True) - rb_manual4.join_group(rb_dhcp4) + self.rb_manual4.set_active(True) + self.rb_manual4.join_group(self.rb_dhcp4) radioButtonLabel = Gtk.Label(label="IPv4 Method:") radioButtonLabel.set_margin_top(15) @@ -113,8 +120,8 @@ def __init__(self, defaultactiveint): radioBox = Gtk.Box(orientation=0, spacing=50) radioBox.set_homogeneous(False) radioBox.pack_start(radioButtonLabel, False, False, 0) - radioBox.pack_start(rb_dhcp4, True, False, 0) - radioBox.pack_end(rb_manual4, True, True, 0) + radioBox.pack_start(self.rb_dhcp4, True, False, 0) + radioBox.pack_end(self.rb_manual4, True, True, 0) # Add Manual Address Field ipInputAddressLabel = Gtk.Label(label="Address") @@ -192,14 +199,18 @@ def __init__(self, defaultactiveint): searchBox = Gtk.Box(orientation=0, spacing=0) searchBox.pack_start(searchLabel, False, False, 0) searchBox.pack_end(self.searchEntry, True, True, 0) - if currentSettings["Address Assignment Method"] == "DHCP": + + self.rb_dhcp4.connect("toggled", self.edit_ipv4_setting) + self.rb_manual4.connect("toggled", self.edit_ipv4_setting) + + if currentSettings["Assignment Method"] == "DHCP": self.ipInputAddressEntry.set_sensitive(False) self.ipInputMaskEntry.set_sensitive(False) self.ipInputGatewayEntry.set_sensitive(False) self.prymary_dnsEntry.set_sensitive(False) self.secondary_dnsEntry.set_sensitive(False) self.searchEntry.set_sensitive(False) - # Build the grid, which will handle the physical layout of the UI elements. + gridOne = Gtk.Grid() gridOne.set_column_homogeneous(True) gridOne.set_row_homogeneous(False) @@ -224,17 +235,16 @@ def __init__(self, defaultactiveint): # Add interfaces to a ListStore store6 = Gtk.ListStore(str) - validinterfaces6 = self.enumerate_nics() - for validinterface6 in validinterfaces6: + for validinterface6 in self.NICS: store6.append([validinterface6]) - # Build the UI aspects of the ComboBox, passing the interface clicked in the trayicon - # as the interface that needs to be the active one when the combo box is drawn - activeComboBoxObjectIndex6 = validinterfaces6.index(f"{defaultactiveint}") interfaceComboBox6.set_model(store) interfaceComboBox6.set_margin_top(15) interfaceComboBox6.set_margin_end(30) - interfaceComboBox6.set_active(activeComboBoxObjectIndex6) + + if DEFAULT_NIC: + activeComboBoxObjectIndex6 = self.NICS.index(f"{DEFAULT_NIC}") + interfaceComboBox6.set_active(activeComboBoxObjectIndex6) interfaceComboBox6.connect("changed", self.cbox_config_refresh) # Build Label to sit in front of the ComboBox @@ -251,7 +261,8 @@ def __init__(self, defaultactiveint): rb_slaac6 = Gtk.RadioButton.new_with_label(None, "SLAAC") rb_slaac6.set_margin_top(15) rb_slaac6.connect("toggled", self.edit_ipv6_setting, "SLAAC") - rb_manual6 = Gtk.RadioButton.new_with_label_from_widget(rb_slaac6, "Manual") + rb_manual6 = Gtk.RadioButton.new_with_label_from_widget( + rb_slaac6, "Manual") rb_manual6.set_margin_top(15) rb_manual6.join_group(rb_slaac6) rb_manual6.connect("toggled", self.edit_ipv6_setting, "Manual") @@ -332,7 +343,7 @@ def __init__(self, defaultactiveint): self.ipInputGatewayEntry6.set_sensitive(False) self.prymary_dnsEntry6.set_sensitive(False) self.searchEntry6.set_sensitive(False) - # Build the grid, which will handle the physical layout of the UI elements. + gridOne6 = Gtk.Grid() gridOne6.set_column_homogeneous(True) gridOne6.set_row_homogeneous(False) @@ -361,7 +372,7 @@ def __init__(self, defaultactiveint): self.saveButton.set_margin_bottom(10) self.saveButton.set_margin_start(10) self.saveButton.connect("clicked", self.commit_pending_changes) - if currentSettings["Address Assignment Method"] == "DHCP": + if currentSettings["Assignment Method"] == "DHCP": self.saveButton.set_sensitive(False) cancelButton = Gtk.Button(label="Cancel") cancelButton.set_margin_bottom(10) @@ -383,167 +394,151 @@ def __init__(self, defaultactiveint): mainBox.pack_end(buttonsWindow, False, False, 0) self.add(mainBox) - # Run any functions that need to execute once at window creation - self.cbox_config_refresh(interfaceComboBox) - - # Returns a list of valid configurable interfaces. - def enumerate_nics(self): - validnics = list() - confnotnics = ["lo", "fwe", "fwip", "tap", "plip", "pfsync", "pflog", - "tun", "sl", "faith", "ppp", "bridge", "ixautomation", - "wg"] - confncard = 'ifconfig -l' - confnics = Popen(confncard, shell=True, stdout=PIPE, close_fds=True, universal_newlines=True) - confnetcard = confnics.stdout.readlines()[0].rstrip() - confnetcardarray = confnetcard.split(" ") - for confnic in confnetcardarray: - nicgeneralized = re.findall("[a-zA-Z]+", confnic) - stringnicgeneralized = str(nicgeneralized).replace("'", "") - stringnicgeneralized = stringnicgeneralized.replace("[", "") - stringnicgeneralized = stringnicgeneralized.replace("]", "") - if stringnicgeneralized in confnotnics: - print(f"{confnic} was generalized to {nicgeneralized} and was found in the notnics list! " - "It will not be added to the valid configurable nic list in the netCardConfigWindow.enumerate_nics method.") - else: - validnics.append(confnic) - return validnics - - # Used with the combo box to refresh the UI of tab 1 with active settings for the newly selected active interface. - def cbox_config_refresh(self, widget): - refreshedInterface = widget.get_active() - refreshedInterfaceName = self.enumerate_nics()[refreshedInterface] + # Used with the combo box to refresh the UI of tab 1 with active settings + # for the newly selected active interface. + def cbox_config_refresh(self, widget, nics): # actions here need to refresh the values on the first two tabs. - print(f"Refreshing settings to match current settings on {refreshedInterface}. " - f"Interface name is {refreshedInterfaceName}") - self.get_current_interface_settings(refreshedInterfaceName) - # self.display_current_interface_settings(widget) + self.get_current_interface_settings(nics[widget.get_active()]) + self.update_interface_settings() def get_current_interface_settings(self, active_nic): # Need to accurately determine if a wlanN interface is using DHCP - aInt = str(active_nic) - - DHCPStatus = os.path.exists(f"/var/db/dhclient.leases.{aInt}") - print(f"dhcpstatus return value = {DHCPStatus}") - if DHCPStatus is False: - RCConf = open("/etc/rc.conf", "r").read() - DHCPSearch = re.findall(f"^ifconfig_{aInt}=\".*DHCP", RCConf) - print(f"DHCPSearch is {DHCPSearch} and the length is {len(DHCPSearch)}") - if len(DHCPSearch) < 1: - DHCPStatusOutput = "Manual" - else: - DHCPStatusOutput = "DHCP" + + rc_conf = open("/etc/rc.conf", "r").read() + DHCPSearch = re.findall(fr'^ifconfig_{active_nic}=".*DHCP', rc_conf, re.MULTILINE) + print(f"DHCPSearch is {DHCPSearch} and the length is {len(DHCPSearch)}") + if len(DHCPSearch) < 1: + DHCPStatusOutput = "Manual" else: DHCPStatusOutput = "DHCP" - print(f"DHCPStatusOutput = {DHCPStatusOutput}") - - ifconfigaInt = f"ifconfig -f inet:dotted {aInt}" - ifconfigaIntOutput = check_output(ifconfigaInt.split(" ")) - - aIntIP = re.findall(r'inet [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+', str(ifconfigaIntOutput))[0] - aIntIPStrip = str(aIntIP).replace("inet ", "") - aIntIPStrip = str(aIntIPStrip).replace("'", "") - aIntIPStrip = str(aIntIPStrip).replace("[", "") - aIntIPStrip = str(aIntIPStrip).replace("]", "") - aIntMask = re.findall(r'netmask [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+', str(ifconfigaIntOutput))[0] - aIntMaskStrip = str(aIntMask).replace("netmask ", "") - aIntMaskStrip = str(aIntMaskStrip).replace("'", "") - aIntMaskStrip = str(aIntMaskStrip).replace("[", "") - aIntMaskStrip = str(aIntMaskStrip).replace("]", "") - aIntBroadcast = re.findall(r'broadcast [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+', str(ifconfigaIntOutput))[0] - aIntBroadcastStrip = str(aIntBroadcast).replace("broadcast ", "") - aIntBroadcastStrip = str(aIntBroadcastStrip).replace("'", "") - aIntBroadcastStrip = str(aIntBroadcastStrip).replace("[", "") - aIntBroadcastStrip = str(aIntBroadcastStrip).replace("]", "") + IPREGEX = r'[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' + ifcmd = f"ifconfig -f inet:dotted {active_nic}" + ifoutput = check_output(ifcmd.split(" "), universal_newlines=True) + re_ip = re.search(fr'inet {IPREGEX}', ifoutput) + if_ip = re_ip.group().replace("inet ", "").strip() + re_netmask = re.search(fr'netmask {IPREGEX}', ifoutput) + if_netmask = re_netmask.group().replace("netmask ", "").strip() + re_broadcast = re.search(fr'broadcast {IPREGEX}', ifoutput) + if_broadcast = re_broadcast.group().replace("broadcast ", "").strip() if (DHCPStatusOutput == "DHCP"): - print(f"{DHCPStatusOutput}") - DHClientFileTest = os.path.exists(f"/var/db/dhclient.leases.{aInt}") - if DHClientFileTest is False: - print(f"dhclientfiletest = {DHClientFileTest}") - # RenewDHCP = f"dhclient {aInt}" - # RenewDHCPOutput = subprocess.check_output(RenewDHCP.split(" ")) - sleep(5) - DHClientFileTest = os.path.exists(f"/var/db/dhclient.leases.{aInt}") - if DHClientFileTest is False: - print(f"DHCP is enabled, but we're unable to read the lease file a /var/db/dhclient.leases.{aInt}") - aIntGatewayStrip = "" + dhclient_leases = f"/var/db/dhclient.leases.{active_nic}" + + if os.path.exists(dhclient_leases) is False: + print("DHCP is enabled, but we're unable to read the lease " + f"file a /var/db/dhclient.leases.{active_nic}") + gateway = "" else: - DHCPLeaseInfo = open(f"/var/db/dhclient.leases.{aInt}", "r").read() - aIntGateway = re.findall(r"option routers [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+;", DHCPLeaseInfo)[0] - aIntGatewayStrip = str(aIntGateway).replace("option routers ", "") - aIntGatewayStrip = str(aIntGatewayStrip).replace("'", "") - aIntGatewayStrip = str(aIntGatewayStrip).replace("[", "") - aIntGatewayStrip = str(aIntGatewayStrip).replace("]", "") - aIntGatewayStrip = str(aIntGatewayStrip).replace(";", "") - - # aIntDHCP = f"resolvconf -l {aInt}" - # aIntDHCPResults = subprocess.check_output(aIntDHCP.split(" ")) - # aIntDHCPResults = subprocess.run(aIntDHCP.split(" "), - # capture_output=True, - # text=True) - # DNSMatch = re.findall(r'nameserver [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+', str(aIntDHCPResults)) - DefaultDNSServers = open('/etc/resolv.conf').read() - DNSMatch = re.findall(r'nameserver [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+', str(DefaultDNSServers)) - - SearchDomainMatch = re.findall('search [a-zA-Z.]*', str(DefaultDNSServers)) - if len(SearchDomainMatch) < 1: - RCConfDomainSearch = open('/etc/resolv.conf', 'r').read() - SearchDomainMatch = re.findall('domain (.*)', RCConfDomainSearch) - SearchDomainMatchStrip = str(SearchDomainMatch).replace("domain ", "") - SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("'", "") - SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("[", "") - SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("]", "") - SearchDomainMatchStrip = SearchDomainMatchStrip.replace('search', '').strip() + dh_lease = open(dhclient_leases, "r").read() + re_gateway = re.search(fr"option routers {IPREGEX}", dh_lease) + gateway = re_gateway.group().replace("option routers ", "") else: - RRConfGatewaySearch = open('/etc/rc.conf', 'r').read() - RRConfGatewayResults = re.findall(r'defaultrouter="[0-9]+\.[0-9]+\.[0-9]+\.[0-9]"', RRConfGatewaySearch) - aIntGatewayStrip = str(RRConfGatewayResults).replace('defaultrouter="', "") - aIntGatewayStrip = str(aIntGatewayStrip).replace('"', "") - aIntGatewayStrip = str(aIntGatewayStrip).replace('[', "") - aIntGatewayStrip = str(aIntGatewayStrip).replace(']', "") - aIntGatewayStrip = str(aIntGatewayStrip).replace("'", "") - - DefaultDNSServers = open('/etc/resolv.conf').read() - DNSMatch = re.findall(r'nameserver [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+', str(DefaultDNSServers)) - - RCConfDomainSearch = open('/etc/resolv.conf', 'r').read() - SearchDomainMatch = re.findall('domain (.*)', RCConfDomainSearch) - SearchDomainMatchStrip = str(SearchDomainMatch).replace("domain ", "") - SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("'", "") - SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("[", "") - SearchDomainMatchStrip = str(SearchDomainMatchStrip).replace("]", "") - SearchDomainMatchStrip = SearchDomainMatchStrip.replace('search', '').strip() - - # currentSettings = {} - currentSettings["Active Interface"] = active_nic - currentSettings["Address Assignment Method"] = DHCPStatusOutput - currentSettings["Interface IP"] = aIntIPStrip - currentSettings["Interface Subnet Mask"] = aIntMaskStrip - currentSettings["Broadcast Address"] = aIntBroadcastStrip - currentSettings["Default Gateway"] = aIntGatewayStrip - # [currentSettings.append(str(DNSServer).replace("nameserver ", "")) for DNSServer in DNSMatch] - currentSettings["Search Domain"] = SearchDomainMatchStrip + rc_conf = open('/etc/rc.conf', 'r').read() + re_gateway = re.search(fr'^defaultrouter="{IPREGEX}"', rc_conf, re.MULTILINE) + gateway = re_gateway.group().replace('"', "") + gateway = gateway.replace('defaultrouter=', "") + + if os.path.exists('/etc/resolv.conf'): + resolv_conf = open('/etc/resolv.conf').read() + nameservers = re.findall(fr'^nameserver {IPREGEX}', str(resolv_conf), re.MULTILINE) + print(nameservers) + + re_domain_search = re.findall('search [a-zA-Z.]*', str(resolv_conf)) + if len(re_domain_search) < 1: + re_domain_search = re.findall('domain (.*)', resolv_conf) + domain_search = str(re_domain_search).replace("domain ", "") + domain_search = domain_search.replace("'", "") + domain_search = domain_search.replace("[", "") + domain_search = domain_search.replace("]", "") + domain_search = domain_search.replace('search', '').strip() + else: + domain_search = '' + nameservers = [] - for num in range(len(DNSMatch)): - currentSettings[f"DNS Server {num + 1}"] = str(DNSMatch[(num)]).replace("nameserver", "").strip() + currentSettings["Active Interface"] = active_nic + currentSettings["Assignment Method"] = DHCPStatusOutput + currentSettings["Interface IP"] = if_ip + currentSettings["Interface Subnet Mask"] = if_netmask + currentSettings["Broadcast Address"] = if_broadcast + currentSettings["Default Gateway"] = gateway + currentSettings["Search Domain"] = domain_search + + for num in range(len(nameservers)): + currentSettings[ + f"DNS Server {num + 1}" + ] = str(nameservers[(num)]).replace("nameserver", "").strip() print("Current settings are below:") print(f"{currentSettings}") - def display_current_interface_settings(self, widget): - print("display_current_interface_settings_go_here") + def update_interface_settings(self): + self.ipInputAddressEntry.set_text(currentSettings["Interface IP"]) + self.ipInputMaskEntry.set_text(currentSettings["Interface Subnet Mask"]) + self.ipInputGatewayEntry.set_text(currentSettings["Default Gateway"]) + self.prymary_dnsEntry.set_text(currentSettings["DNS Server 1"]) + self.secondary_dnsEntry.set_text(currentSettings["DNS Server 2"]) + self.searchEntry.set_text(currentSettings["Search Domain"]) + if currentSettings["Assignment Method"] == "DHCP": + self.rb_dhcp4.set_active(True) + else: + self.rb_manual4.set_active(True) def commit_pending_changes(self, widget): - print("commit_pending_changes_goes_here") + nic = currentSettings["Active Interface"] + inet = self.ipInputAddressEntry.get_text() + netmask = self.ipInputMaskEntry.get_text() + defaultrouter = self.ipInputGatewayEntry.get_text() + if self.method == 'Manual': + ifconfig_nic = f'ifconfig_{nic}="inet {inet} netmask {netmask}"\n' + self.update_rc_conf(ifconfig_nic) + defaultrouter_line = f'defaultrouter="{defaultrouter}"\n' + self.update_rc_conf(defaultrouter_line) + + resolv_conf = open('/etc/resolv.conf', 'w') + resolv_conf.writelines('# Generated by NetworkMgr\n') + search = self.searchEntry.get_text() + search_line = f'search {search}\n' + resolv_conf.writelines(search_line) + dns1 = self.prymary_dnsEntry.get_text() + nameserver1_line = f'nameserver {dns1}\n' + resolv_conf.writelines(nameserver1_line) + dns2 = self.secondary_dnsEntry.get_text() + nameserver2_line = f'nameserver {dns2}\n' + resolv_conf.writelines(nameserver2_line) + resolv_conf.close() + start_static_network(nic, inet, netmask) + else: + ifconfig_nic = f'ifconfig_{nic}="DHCP"\n' + self.update_rc_conf(ifconfig_nic) + + rc_conf = open('/etc/rc.conf', 'r').read() + for nic_search in self.NICS: + if re.search(f'^ifconfig_{nic_search}="inet', rc_conf, re.MULTILINE): + break + else: + defaultrouter_line = f'defaultrouter="{defaultrouter}"\n' + self.remove_rc_conf_line(defaultrouter_line) + restart_dhcp_network(nic) def discard_pending_changes(self, widget): - print("discard_pending_changes_goes_here") self.destroy() + def update_rc_conf(self, line): + run(f'sysrc {line}', shell=True) + + def remove_rc_conf_line(self, line): + with open('/etc/rc.conf', "r+") as rc_conf: + lines = rc_conf.readlines() + rc_conf.seek(0) + idx = lines.index(line) + lines.pop(idx) + rc_conf.truncate() + rc_conf.writelines(lines) + -def openNetCardConfigwindow(default_int): - win = netCardConfigWindow(default_int) - win.connect("destroy", Gtk.main_quit) - win.show_all() - Gtk.main() +# def openNetCardConfigwindow(default_int): +win = netCardConfigWindow('wlan0') +win.connect("destroy", Gtk.main_quit) +win.show_all() +Gtk.main() From 02745b536eb1a4b8a7488c16cd2b53d74022e2b3 Mon Sep 17 00:00:00 2001 From: ericbsd Date: Sat, 22 Jul 2023 22:14:01 -0300 Subject: [PATCH 22/24] Fixed issues with wlan and rename netcardmgr to network_configuration also changed networkmg module to be proper python module --- .../configuration.py | 92 +++++++++++++------ {src => NetworkMgr}/net_api.py | 72 +++++++++------ {src => NetworkMgr}/trayicon.py | 28 +++--- networkmgr | 11 +-- networkmgr_configuration | 8 ++ setup.py | 20 ++-- 6 files changed, 142 insertions(+), 89 deletions(-) rename src/netcardmgr.py => NetworkMgr/configuration.py (90%) rename {src => NetworkMgr}/net_api.py (81%) rename {src => NetworkMgr}/trayicon.py (98%) create mode 100755 networkmgr_configuration diff --git a/src/netcardmgr.py b/NetworkMgr/configuration.py similarity index 90% rename from src/netcardmgr.py rename to NetworkMgr/configuration.py index 1ced5d4..3b11ad1 100755 --- a/src/netcardmgr.py +++ b/NetworkMgr/configuration.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python3 +#!/usr/bin/env python import gi gi.require_version('Gtk', '3.0') @@ -6,11 +6,13 @@ from subprocess import check_output, run import os import re -from net_api import ( - start_static_network, - nics_list, +from NetworkMgr.net_api import ( defaultcard, - restart_dhcp_network + nics_list, + restart_card_network, + restart_rounting_and_dhcp, + start_static_network, + wait_inet ) rcconf = open('/etc/rc.conf', 'r').read() if os.path.exists('/etc/rc.conf.local'): @@ -62,7 +64,7 @@ def edit_ipv6_setting(self, widget, value): def __init__(self, selected_nic=None): # Build Default Window - Gtk.Window.__init__(self, title="Network Interface Configuration") + Gtk.Window.__init__(self, title="Network Configuration") self.set_default_size(475, 400) self.NICS = nics_list() DEFAULT_NIC = selected_nic if selected_nic else defaultcard() @@ -372,8 +374,7 @@ def __init__(self, selected_nic=None): self.saveButton.set_margin_bottom(10) self.saveButton.set_margin_start(10) self.saveButton.connect("clicked", self.commit_pending_changes) - if currentSettings["Assignment Method"] == "DHCP": - self.saveButton.set_sensitive(False) + self.saveButton.set_sensitive(False) cancelButton = Gtk.Button(label="Cancel") cancelButton.set_margin_bottom(10) cancelButton.connect("clicked", self.discard_pending_changes) @@ -393,6 +394,7 @@ def __init__(self, selected_nic=None): mainBox.pack_start(nb, True, True, 0) mainBox.pack_end(buttonsWindow, False, False, 0) self.add(mainBox) + self.show_all() # Used with the combo box to refresh the UI of tab 1 with active settings # for the newly selected active interface. @@ -417,11 +419,16 @@ def get_current_interface_settings(self, active_nic): ifcmd = f"ifconfig -f inet:dotted {active_nic}" ifoutput = check_output(ifcmd.split(" "), universal_newlines=True) re_ip = re.search(fr'inet {IPREGEX}', ifoutput) - if_ip = re_ip.group().replace("inet ", "").strip() - re_netmask = re.search(fr'netmask {IPREGEX}', ifoutput) - if_netmask = re_netmask.group().replace("netmask ", "").strip() - re_broadcast = re.search(fr'broadcast {IPREGEX}', ifoutput) - if_broadcast = re_broadcast.group().replace("broadcast ", "").strip() + if re_ip: + if_ip = re_ip.group().replace("inet ", "").strip() + re_netmask = re.search(fr'netmask {IPREGEX}', ifoutput) + if_netmask = re_netmask.group().replace("netmask ", "").strip() + re_broadcast = re.search(fr'broadcast {IPREGEX}', ifoutput) + if_broadcast = re_broadcast.group().replace("broadcast ", "").strip() + else: + if_ip = "" + if_netmask = "" + if_broadcast = "" if (DHCPStatusOutput == "DHCP"): dhclient_leases = f"/var/db/dhclient.leases.{active_nic}" @@ -436,8 +443,11 @@ def get_current_interface_settings(self, active_nic): else: rc_conf = open('/etc/rc.conf', 'r').read() re_gateway = re.search(fr'^defaultrouter="{IPREGEX}"', rc_conf, re.MULTILINE) - gateway = re_gateway.group().replace('"', "") - gateway = gateway.replace('defaultrouter=', "") + if re_gateway: + gateway = re_gateway.group().replace('"', "") + gateway = gateway.replace('defaultrouter=', "") + else: + gateway = "" if os.path.exists('/etc/resolv.conf'): resolv_conf = open('/etc/resolv.conf').read() @@ -468,6 +478,11 @@ def get_current_interface_settings(self, active_nic): currentSettings[ f"DNS Server {num + 1}" ] = str(nameservers[(num)]).replace("nameserver", "").strip() + # if DNS Server 1 and 2 are missing create them with empty string + if "DNS Server 1" not in currentSettings: + currentSettings["DNS Server 1"] = "" + if "DNS Server 2" not in currentSettings: + currentSettings["DNS Server 2"] = "" print("Current settings are below:") print(f"{currentSettings}") @@ -490,36 +505,48 @@ def commit_pending_changes(self, widget): netmask = self.ipInputMaskEntry.get_text() defaultrouter = self.ipInputGatewayEntry.get_text() if self.method == 'Manual': - ifconfig_nic = f'ifconfig_{nic}="inet {inet} netmask {netmask}"\n' + if 'wlan' in nic: + ifconfig_nic = f'ifconfig_{nic}="WPA inet {inet} netmask {netmask}"\n' + else: + ifconfig_nic = f'ifconfig_{nic}="inet {inet} netmask {netmask}"\n' self.update_rc_conf(ifconfig_nic) defaultrouter_line = f'defaultrouter="{defaultrouter}"\n' self.update_rc_conf(defaultrouter_line) - + start_static_network(nic, inet, netmask) resolv_conf = open('/etc/resolv.conf', 'w') resolv_conf.writelines('# Generated by NetworkMgr\n') search = self.searchEntry.get_text() - search_line = f'search {search}\n' - resolv_conf.writelines(search_line) + if search: + search_line = f'search {search}\n' + resolv_conf.writelines(search_line) dns1 = self.prymary_dnsEntry.get_text() nameserver1_line = f'nameserver {dns1}\n' resolv_conf.writelines(nameserver1_line) dns2 = self.secondary_dnsEntry.get_text() - nameserver2_line = f'nameserver {dns2}\n' - resolv_conf.writelines(nameserver2_line) + if dns2: + nameserver2_line = f'nameserver {dns2}\n' + resolv_conf.writelines(nameserver2_line) resolv_conf.close() - start_static_network(nic, inet, netmask) else: - ifconfig_nic = f'ifconfig_{nic}="DHCP"\n' + if 'wlan' in nic: + ifconfig_nic = f'ifconfig_{nic}="WPA DHCP"\n' + else: + ifconfig_nic = f'ifconfig_{nic}="DHCP"\n' self.update_rc_conf(ifconfig_nic) rc_conf = open('/etc/rc.conf', 'r').read() for nic_search in self.NICS: - if re.search(f'^ifconfig_{nic_search}="inet', rc_conf, re.MULTILINE): + if re.search(f'^ifconfig_{nic_search}=".*inet', rc_conf, re.MULTILINE): break else: defaultrouter_line = f'defaultrouter="{defaultrouter}"\n' self.remove_rc_conf_line(defaultrouter_line) - restart_dhcp_network(nic) + restart_card_network(nic) + self.hide() + wait_inet(nic) + restart_rounting_and_dhcp(nic) + + self.destroy() def discard_pending_changes(self, widget): self.destroy() @@ -537,8 +564,13 @@ def remove_rc_conf_line(self, line): rc_conf.writelines(lines) -# def openNetCardConfigwindow(default_int): -win = netCardConfigWindow('wlan0') -win.connect("destroy", Gtk.main_quit) -win.show_all() -Gtk.main() +def network_card_configuration(default_int): + win = netCardConfigWindow(default_int) + win.connect("destroy", Gtk.main_quit) + Gtk.main() + + +def network_card_configuration_window(): + win = netCardConfigWindow() + win.connect("destroy", Gtk.main_quit) + Gtk.main() diff --git a/src/net_api.py b/NetworkMgr/net_api.py similarity index 81% rename from src/net_api.py rename to NetworkMgr/net_api.py index bb1c5d1..8bf2db4 100755 --- a/src/net_api.py +++ b/NetworkMgr/net_api.py @@ -1,11 +1,8 @@ -#!/usr/bin/env python3 +#!/usr/bin/env python -from subprocess import Popen, PIPE, run -from sys import path -import os +from subprocess import Popen, PIPE, run, check_output import re from time import sleep -path.append("/usr/local/share/networkmgr") def card_online(netcard): @@ -194,64 +191,67 @@ def switch_default(nic): ).stdout.read() if 'status: active' in nic_info or 'status: associated' in nic_info: if 'inet ' in nic_info or 'inet6' in nic_info: - os.system(f'service dhclient restart {card}') + run(f'service dhclient restart {card}', shell=True) break return def stopallnetwork(): - os.system('service netif stop') + run('service netif stop', shell=True) def startallnetwork(): - os.system('service netif start') + run('service netif start', shell=True) def stopnetworkcard(netcard): - os.system(f'service netif stop {netcard}') + run(f'service netif stop {netcard}', shell=True) switch_default(netcard) -def restart_dhcp_network(netcard): - os.system(f'service netif restart {netcard}') +def restart_card_network(netcard): + run(f'service netif restart {netcard}', shell=True) + + +def restart_rounting_and_dhcp(netcard): + run('service routing restart', shell=True) sleep(1) - # os.system('service routing restart') - # os.system(f'service dhclient restart {netcard}') + run(f'service dhclient restart {netcard}', shell=True) def start_static_network(netcard, inet, netmask): - os.system(f'ifconfig {netcard} inet {inet} netmask {netmask}') + run(f'ifconfig {netcard} inet {inet} netmask {netmask}', shell=True) sleep(1) - os.system('service routing restart') + run('service routing restart', shell=True) def startnetworkcard(netcard): - os.system(f'service netif start {netcard}') + run(f'service netif start {netcard}', shell=True) sleep(1) - os.system('service routing restart') - os.system(f'service dhclient start {netcard}') + run('service routing restart', shell=True) + run(f'service dhclient start {netcard}', shell=True) def wifiDisconnection(wificard): - os.system(f'ifconfig {wificard} down') - os.system(f"ifconfig {wificard} ssid 'none'") - os.system(f'ifconfig {wificard} up') + run(f'ifconfig {wificard} down', shell=True) + run(f"ifconfig {wificard} ssid 'none'", shell=True) + run(f'ifconfig {wificard} up', shell=True) def disableWifi(wificard): - os.system(f'ifconfig {wificard} down') + run(f'ifconfig {wificard} down', shell=True) def enableWifi(wificard): - os.system(f'ifconfig {wificard} up') - os.system(f'ifconfig {wificard} up scan') + run(f'ifconfig {wificard} up', shell=True) + run(f'ifconfig {wificard} up scan', shell=True) def connectToSsid(name, wificard): - os.system('killall wpa_supplicant') + run('killall wpa_supplicant', shell=True) # service sleep(0.5) - os.system(f"ifconfig {wificard} ssid '{name}'") + run(f"ifconfig {wificard} ssid '{name}'", shell=True) sleep(0.5) wpa_supplicant = run( f'wpa_supplicant -B -i {wificard} -c /etc/wpa_supplicant.conf', @@ -288,7 +288,7 @@ def delete_ssid_wpa_supplicant_config(ssid): wpa_supplicant_conf.close() -def wlan_status(card): +def nic_status(card): out = Popen( f'ifconfig {card} | grep status:', shell=True, stdout=PIPE, @@ -298,4 +298,20 @@ def wlan_status(card): def start_dhcp(wificard): - os.system(f'dhclient {wificard}') + run(f'dhclient {wificard}', shell=True) + + +def wait_inet(card): + IPREGEX = r'[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' + status = 'associated' if 'wlan' in card else 'active' + while nic_status(card) != status: + sleep(0.1) + print(nic_status(card)) + while True: + ifcmd = f"ifconfig -f inet:dotted {card}" + ifoutput = check_output(ifcmd.split(" "), universal_newlines=True) + print(ifoutput) + re_ip = re.search(fr'inet {IPREGEX}', ifoutput) + if re_ip and '0.0.0.0' not in re_ip.group(): + print(re_ip) + break diff --git a/src/trayicon.py b/NetworkMgr/trayicon.py similarity index 98% rename from src/trayicon.py rename to NetworkMgr/trayicon.py index 9acbcd2..fd66ed5 100755 --- a/src/trayicon.py +++ b/NetworkMgr/trayicon.py @@ -1,21 +1,14 @@ -#!/usr/bin/env python3 +#!/usr/bin/env python import gi gi.require_version('Gtk', '3.0') -from gi.repository import Gtk, GObject, GLib import gettext -from time import sleep import threading import _thread -from sys import path import locale - -gettext.bindtextdomain('networkmgr', '/usr/local/share/locale') -gettext.textdomain('networkmgr') -_ = gettext.gettext - -path.append("/usr/local/share/networkmgr") -from net_api import ( +from time import sleep +from gi.repository import Gtk, GObject, GLib +from NetworkMgr.net_api import ( stopnetworkcard, startnetworkcard, wifiDisconnection, @@ -27,9 +20,14 @@ connectionStatus, networkdictionary, delete_ssid_wpa_supplicant_config, - wlan_status + nic_status ) -from netcardmgr import openNetCardConfigwindow +from NetworkMgr.configuration import network_card_configuration + + +gettext.bindtextdomain('networkmgr', '/usr/local/share/locale') +gettext.textdomain('networkmgr') +_ = gettext.gettext encoding = locale.getpreferredencoding() threadBreak = False @@ -192,7 +190,7 @@ def wifiListMenu(self, wificard, cssid, passes, cards): self.menu.append(avconnmenu) def configuration_window_open(self, widget, interface): - openNetCardConfigwindow(interface) + network_card_configuration(interface) def menu_click_open(self, widget, ssid, wificard): if f'"{ssid}"' in open("/etc/wpa_supplicant.conf").read(): @@ -348,7 +346,7 @@ def try_to_connect_to_ssid(self, ssid, ssid_info, card): GLib.idle_add(self.restart_authentication, ssid_info, card) else: for _ in list(range(60)): - if wlan_status(card) == 'associated': + if nic_status(card) == 'associated': self.updateinfo() break sleep(1) diff --git a/networkmgr b/networkmgr index a5a95e9..b804412 100755 --- a/networkmgr +++ b/networkmgr @@ -1,13 +1,8 @@ -#!/usr/bin/env python3 +#!/usr/bin/env python -from os.path import dirname -from sys import path import signal -path.append("/usr/local/share/networkmgr") -path.append(dirname(__file__) + "/src") -from trayicon import trayIcon +from NetworkMgr.trayicon import trayIcon signal.signal(signal.SIGINT, signal.SIG_DFL) -i = trayIcon() -i.tray() +trayIcon().tray() diff --git a/networkmgr_configuration b/networkmgr_configuration new file mode 100755 index 0000000..9b57566 --- /dev/null +++ b/networkmgr_configuration @@ -0,0 +1,8 @@ +#!/usr/bin/env python + +import signal +from NetworkMgr import configuration + +signal.signal(signal.SIGINT, signal.SIG_DFL) + +configuration.network_card_configuration_window() diff --git a/setup.py b/setup.py index 1599677..70ab69d 100755 --- a/setup.py +++ b/setup.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python3 +#!/usr/bin/env python # -*- coding: utf-8 -*- import os @@ -26,17 +26,20 @@ def datafilelist(installbase, sourcebase): return datafileList -share_networkmgr = [ +networkmgr_share = [ 'src/auto-switch.py', - 'src/net_api.py', - 'src/setup-nic.py', - 'src/trayicon.py', - 'src/netcardmgr.py' + 'src/setup-nic.py' +] + +networkmgr_module = [ + 'NetworkMgr/net_api', + 'NetworkMgr/trayicon', + 'NetworkMgr/configuration' ] data_files = [ (f'{prefix}/etc/xdg/autostart', ['src/networkmgr.desktop']), - (f'{prefix}/share/networkmgr', share_networkmgr), + (f'{prefix}/share/networkmgr', networkmgr_share), (f'{prefix}/share/locale/zh_CN/LC_MESSAGES', ['src/locale/zh_CN/networkmgr.mo']), (f'{prefix}/share/locale/ru/LC_MESSAGES', ['src/locale/ru/networkmgr.mo']), (f'{prefix}/etc/sudoers.d', ['src/sudoers.d/networkmgr']) @@ -59,7 +62,8 @@ def datafilelist(installbase, sourcebase): package_dir={'': '.'}, data_files=data_files, install_requires=['setuptools'], - scripts=['networkmgr'] + py_modules=networkmgr_module, + scripts=['networkmgr', 'networkmgr_configuration'] ) run('gtk-update-icon-cache -f /usr/local/share/icons/hicolor', shell=True) From a34aa302757e8f1d7654e3694b3c904971333d2c Mon Sep 17 00:00:00 2001 From: ericbsd Date: Sun, 23 Jul 2023 22:31:54 -0300 Subject: [PATCH 23/24] Adding save button trigger on entry changes Improved window at click save --- NetworkMgr/configuration.py | 165 ++++++++++++------------------------ NetworkMgr/query.py | 88 +++++++++++++++++++ setup.py | 3 +- 3 files changed, 142 insertions(+), 114 deletions(-) create mode 100644 NetworkMgr/query.py diff --git a/NetworkMgr/configuration.py b/NetworkMgr/configuration.py index 3b11ad1..b535fae 100755 --- a/NetworkMgr/configuration.py +++ b/NetworkMgr/configuration.py @@ -1,11 +1,10 @@ #!/usr/bin/env python import gi -gi.require_version('Gtk', '3.0') -from gi.repository import Gtk -from subprocess import check_output, run import os import re +gi.require_version('Gtk', '3.0') +from gi.repository import Gtk, GLib from NetworkMgr.net_api import ( defaultcard, nics_list, @@ -14,15 +13,15 @@ start_static_network, wait_inet ) +from NetworkMgr.query import get_interface_settings +from subprocess import run + rcconf = open('/etc/rc.conf', 'r').read() if os.path.exists('/etc/rc.conf.local'): rcconflocal = open('/etc/rc.conf.local', 'r').read() else: rcconflocal = "None" -global currentSettings -currentSettings = {} - class netCardConfigWindow(Gtk.Window): @@ -41,7 +40,7 @@ def edit_ipv4_setting(self, widget): self.ipInputGatewayEntry.set_sensitive(True) self.prymary_dnsEntry.set_sensitive(True) self.secondary_dnsEntry.set_sensitive(True) - if self.method == currentSettings["Assignment Method"]: + if self.method == self.currentSettings["Assignment Method"]: self.saveButton.set_sensitive(False) else: self.saveButton.set_sensitive(True) @@ -62,6 +61,9 @@ def edit_ipv6_setting(self, widget, value): self.searchEntry6.set_sensitive(True) self.saveButton.set_sensitive(True) + def entry_trigger_save_button(self, widget, event): + self.saveButton.set_sensitive(True) + def __init__(self, selected_nic=None): # Build Default Window Gtk.Window.__init__(self, title="Network Configuration") @@ -69,7 +71,6 @@ def __init__(self, selected_nic=None): self.NICS = nics_list() DEFAULT_NIC = selected_nic if selected_nic else defaultcard() # Build Tab 1 Content - # Interface Drop Down Combo Box cell = Gtk.CellRendererText() @@ -89,7 +90,8 @@ def __init__(self, selected_nic=None): if DEFAULT_NIC: active_index = self.NICS.index(f"{DEFAULT_NIC}") interfaceComboBox.set_active(active_index) - self.get_current_interface_settings(DEFAULT_NIC) + self.currentSettings = get_interface_settings(DEFAULT_NIC) + self.method = self.currentSettings["Assignment Method"] interfaceComboBox.connect("changed", self.cbox_config_refresh, self.NICS) # Build Label to sit in front of the ComboBox @@ -103,13 +105,13 @@ def __init__(self, selected_nic=None): interfaceBox.pack_end(interfaceComboBox, True, True, 0) # Add radio button to toggle DHCP or not - self.version = currentSettings["Assignment Method"] + self.version = self.currentSettings["Assignment Method"] self.rb_dhcp4 = Gtk.RadioButton.new_with_label(None, "DHCP") self.rb_dhcp4.set_margin_top(15) self.rb_manual4 = Gtk.RadioButton.new_with_label_from_widget( self.rb_dhcp4, "Manual") self.rb_manual4.set_margin_top(15) - if currentSettings["Assignment Method"] == "DHCP": + if self.currentSettings["Assignment Method"] == "DHCP": self.rb_dhcp4.set_active(True) else: self.rb_manual4.set_active(True) @@ -137,14 +139,17 @@ def __init__(self, selected_nic=None): self.ipInputAddressEntry = Gtk.Entry() self.ipInputAddressEntry.set_margin_start(15) - self.ipInputAddressEntry.set_text(currentSettings["Interface IP"]) + self.ipInputAddressEntry.set_text(self.currentSettings["Interface IP"]) + self.ipInputAddressEntry.connect("key-release-event", self.entry_trigger_save_button) self.ipInputMaskEntry = Gtk.Entry() - self.ipInputMaskEntry.set_text(currentSettings["Interface Subnet Mask"]) + self.ipInputMaskEntry.set_text(self.currentSettings["Interface Subnet Mask"]) + self.ipInputMaskEntry.connect("key-release-event", self.entry_trigger_save_button) self.ipInputGatewayEntry = Gtk.Entry() self.ipInputGatewayEntry.set_margin_end(15) - self.ipInputGatewayEntry.set_text(currentSettings["Default Gateway"]) + self.ipInputGatewayEntry.set_text(self.currentSettings["Default Gateway"]) + self.ipInputGatewayEntry.connect("key-release-event", self.entry_trigger_save_button) ipInputBox = Gtk.Box(orientation=0, spacing=0) ipInputBox.set_homogeneous(True) @@ -170,11 +175,13 @@ def __init__(self, selected_nic=None): self.prymary_dnsEntry = Gtk.Entry() self.prymary_dnsEntry.set_margin_end(30) - self.prymary_dnsEntry.set_text(currentSettings["DNS Server 1"]) + self.prymary_dnsEntry.set_text(self.currentSettings["DNS Server 1"]) + self.prymary_dnsEntry.connect("key-release-event", self.entry_trigger_save_button) self.secondary_dnsEntry = Gtk.Entry() self.secondary_dnsEntry.set_margin_end(30) - self.secondary_dnsEntry.set_text(currentSettings["DNS Server 2"]) + self.secondary_dnsEntry.set_text(self.currentSettings["DNS Server 2"]) + self.secondary_dnsEntry.connect("key-release-event", self.entry_trigger_save_button) dnsEntryBox1 = Gtk.Box(orientation=0, spacing=0) dnsEntryBox1.pack_start(prymary_dns_Label, False, False, 0) @@ -196,7 +203,8 @@ def __init__(self, selected_nic=None): self.searchEntry.set_margin_top(21) self.searchEntry.set_margin_end(30) self.searchEntry.set_margin_bottom(30) - self.searchEntry.set_text(currentSettings["Search Domain"]) + self.searchEntry.set_text(self.currentSettings["Search Domain"]) + self.searchEntry.connect("key-release-event", self.entry_trigger_save_button) searchBox = Gtk.Box(orientation=0, spacing=0) searchBox.pack_start(searchLabel, False, False, 0) @@ -205,7 +213,7 @@ def __init__(self, selected_nic=None): self.rb_dhcp4.connect("toggled", self.edit_ipv4_setting) self.rb_manual4.connect("toggled", self.edit_ipv4_setting) - if currentSettings["Assignment Method"] == "DHCP": + if self.currentSettings["Assignment Method"] == "DHCP": self.ipInputAddressEntry.set_sensitive(False) self.ipInputMaskEntry.set_sensitive(False) self.ipInputGatewayEntry.set_sensitive(False) @@ -291,9 +299,12 @@ def __init__(self, selected_nic=None): self.ipInputAddressEntry6 = Gtk.Entry() self.ipInputAddressEntry6.set_margin_start(15) + self.ipInputAddressEntry6.connect("key-release-event", self.entry_trigger_save_button) self.ipInputMaskEntry6 = Gtk.Entry() + self.ipInputAddressEntry6.connect("key-release-event", self.entry_trigger_save_button) self.ipInputGatewayEntry6 = Gtk.Entry() self.ipInputGatewayEntry6.set_margin_end(15) + self.ipInputGatewayEntry6.connect("key-release-event", self.entry_trigger_save_button) ipInputBox6 = Gtk.Box(orientation=0, spacing=0) ipInputBox6.set_homogeneous(True) @@ -319,6 +330,7 @@ def __init__(self, selected_nic=None): self.prymary_dnsEntry6 = Gtk.Entry() self.prymary_dnsEntry6.set_margin_end(30) + self.prymary_dnsEntry6.connect("key-release-event", self.entry_trigger_save_button) dnsEntryBox6 = Gtk.Box(orientation=0, spacing=0) dnsEntryBox6.pack_start(prymary_dns_Label6, False, False, 0) @@ -335,6 +347,7 @@ def __init__(self, selected_nic=None): self.searchEntry6.set_margin_top(21) self.searchEntry6.set_margin_end(30) self.searchEntry6.set_margin_bottom(30) + self.searchEntry6.connect("key-release-event", self.entry_trigger_save_button) searchBox6 = Gtk.Box(orientation=0, spacing=0) searchBox6.pack_start(searchLabel6, False, False, 0) @@ -394,113 +407,32 @@ def __init__(self, selected_nic=None): mainBox.pack_start(nb, True, True, 0) mainBox.pack_end(buttonsWindow, False, False, 0) self.add(mainBox) - self.show_all() # Used with the combo box to refresh the UI of tab 1 with active settings # for the newly selected active interface. def cbox_config_refresh(self, widget, nics): # actions here need to refresh the values on the first two tabs. - self.get_current_interface_settings(nics[widget.get_active()]) + self.currentSettings = get_interface_settings(nics[widget.get_active()]) self.update_interface_settings() - def get_current_interface_settings(self, active_nic): - # Need to accurately determine if a wlanN interface is using DHCP - - rc_conf = open("/etc/rc.conf", "r").read() - DHCPSearch = re.findall(fr'^ifconfig_{active_nic}=".*DHCP', rc_conf, re.MULTILINE) - print(f"DHCPSearch is {DHCPSearch} and the length is {len(DHCPSearch)}") - if len(DHCPSearch) < 1: - DHCPStatusOutput = "Manual" - else: - DHCPStatusOutput = "DHCP" - - IPREGEX = r'[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' - - ifcmd = f"ifconfig -f inet:dotted {active_nic}" - ifoutput = check_output(ifcmd.split(" "), universal_newlines=True) - re_ip = re.search(fr'inet {IPREGEX}', ifoutput) - if re_ip: - if_ip = re_ip.group().replace("inet ", "").strip() - re_netmask = re.search(fr'netmask {IPREGEX}', ifoutput) - if_netmask = re_netmask.group().replace("netmask ", "").strip() - re_broadcast = re.search(fr'broadcast {IPREGEX}', ifoutput) - if_broadcast = re_broadcast.group().replace("broadcast ", "").strip() - else: - if_ip = "" - if_netmask = "" - if_broadcast = "" - if (DHCPStatusOutput == "DHCP"): - dhclient_leases = f"/var/db/dhclient.leases.{active_nic}" - - if os.path.exists(dhclient_leases) is False: - print("DHCP is enabled, but we're unable to read the lease " - f"file a /var/db/dhclient.leases.{active_nic}") - gateway = "" - else: - dh_lease = open(dhclient_leases, "r").read() - re_gateway = re.search(fr"option routers {IPREGEX}", dh_lease) - gateway = re_gateway.group().replace("option routers ", "") - else: - rc_conf = open('/etc/rc.conf', 'r').read() - re_gateway = re.search(fr'^defaultrouter="{IPREGEX}"', rc_conf, re.MULTILINE) - if re_gateway: - gateway = re_gateway.group().replace('"', "") - gateway = gateway.replace('defaultrouter=', "") - else: - gateway = "" - - if os.path.exists('/etc/resolv.conf'): - resolv_conf = open('/etc/resolv.conf').read() - nameservers = re.findall(fr'^nameserver {IPREGEX}', str(resolv_conf), re.MULTILINE) - print(nameservers) - - re_domain_search = re.findall('search [a-zA-Z.]*', str(resolv_conf)) - if len(re_domain_search) < 1: - re_domain_search = re.findall('domain (.*)', resolv_conf) - domain_search = str(re_domain_search).replace("domain ", "") - domain_search = domain_search.replace("'", "") - domain_search = domain_search.replace("[", "") - domain_search = domain_search.replace("]", "") - domain_search = domain_search.replace('search', '').strip() - else: - domain_search = '' - nameservers = [] - - currentSettings["Active Interface"] = active_nic - currentSettings["Assignment Method"] = DHCPStatusOutput - currentSettings["Interface IP"] = if_ip - currentSettings["Interface Subnet Mask"] = if_netmask - currentSettings["Broadcast Address"] = if_broadcast - currentSettings["Default Gateway"] = gateway - currentSettings["Search Domain"] = domain_search - - for num in range(len(nameservers)): - currentSettings[ - f"DNS Server {num + 1}" - ] = str(nameservers[(num)]).replace("nameserver", "").strip() - # if DNS Server 1 and 2 are missing create them with empty string - if "DNS Server 1" not in currentSettings: - currentSettings["DNS Server 1"] = "" - if "DNS Server 2" not in currentSettings: - currentSettings["DNS Server 2"] = "" - - print("Current settings are below:") - print(f"{currentSettings}") - def update_interface_settings(self): - self.ipInputAddressEntry.set_text(currentSettings["Interface IP"]) - self.ipInputMaskEntry.set_text(currentSettings["Interface Subnet Mask"]) - self.ipInputGatewayEntry.set_text(currentSettings["Default Gateway"]) - self.prymary_dnsEntry.set_text(currentSettings["DNS Server 1"]) - self.secondary_dnsEntry.set_text(currentSettings["DNS Server 2"]) - self.searchEntry.set_text(currentSettings["Search Domain"]) - if currentSettings["Assignment Method"] == "DHCP": + self.ipInputAddressEntry.set_text(self.currentSettings["Interface IP"]) + self.ipInputMaskEntry.set_text(self.currentSettings["Interface Subnet Mask"]) + self.ipInputGatewayEntry.set_text(self.currentSettings["Default Gateway"]) + self.prymary_dnsEntry.set_text(self.currentSettings["DNS Server 1"]) + self.secondary_dnsEntry.set_text(self.currentSettings["DNS Server 2"]) + self.searchEntry.set_text(self.currentSettings["Search Domain"]) + if self.currentSettings["Assignment Method"] == "DHCP": self.rb_dhcp4.set_active(True) else: self.rb_manual4.set_active(True) def commit_pending_changes(self, widget): - nic = currentSettings["Active Interface"] + self.hide_window() + GLib.idle_add(self.update_system) + + def update_system(self): + nic = self.currentSettings["Active Interface"] inet = self.ipInputAddressEntry.get_text() netmask = self.ipInputMaskEntry.get_text() defaultrouter = self.ipInputGatewayEntry.get_text() @@ -542,12 +474,15 @@ def commit_pending_changes(self, widget): defaultrouter_line = f'defaultrouter="{defaultrouter}"\n' self.remove_rc_conf_line(defaultrouter_line) restart_card_network(nic) - self.hide() wait_inet(nic) restart_rounting_and_dhcp(nic) self.destroy() + def hide_window(self): + self.hide() + return False + def discard_pending_changes(self, widget): self.destroy() @@ -567,10 +502,14 @@ def remove_rc_conf_line(self, line): def network_card_configuration(default_int): win = netCardConfigWindow(default_int) win.connect("destroy", Gtk.main_quit) + win.show_all() + win.set_keep_above(True) Gtk.main() def network_card_configuration_window(): win = netCardConfigWindow() win.connect("destroy", Gtk.main_quit) + win.show_all() + win.set_keep_above(True) Gtk.main() diff --git a/NetworkMgr/query.py b/NetworkMgr/query.py new file mode 100644 index 0000000..07b9bc7 --- /dev/null +++ b/NetworkMgr/query.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python + +from subprocess import check_output +import re +import os + + +def get_interface_settings(active_nic): + interface_settings = {} + rc_conf = open("/etc/rc.conf", "r").read() + DHCPSearch = re.findall(fr'^ifconfig_{active_nic}=".*DHCP', rc_conf, re.MULTILINE) + print(f"DHCPSearch is {DHCPSearch} and the length is {len(DHCPSearch)}") + if len(DHCPSearch) < 1: + DHCPStatusOutput = "Manual" + else: + DHCPStatusOutput = "DHCP" + + IPREGEX = r'[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' + + ifcmd = f"ifconfig -f inet:dotted {active_nic}" + ifoutput = check_output(ifcmd.split(" "), universal_newlines=True) + re_ip = re.search(fr'inet {IPREGEX}', ifoutput) + if re_ip: + if_ip = re_ip.group().replace("inet ", "").strip() + re_netmask = re.search(fr'netmask {IPREGEX}', ifoutput) + if_netmask = re_netmask.group().replace("netmask ", "").strip() + re_broadcast = re.search(fr'broadcast {IPREGEX}', ifoutput) + if_broadcast = re_broadcast.group().replace("broadcast ", "").strip() + else: + if_ip = "" + if_netmask = "" + if_broadcast = "" + if (DHCPStatusOutput == "DHCP"): + dhclient_leases = f"/var/db/dhclient.leases.{active_nic}" + + if os.path.exists(dhclient_leases) is False: + print("DHCP is enabled, but we're unable to read the lease " + f"file a /var/db/dhclient.leases.{active_nic}") + gateway = "" + else: + dh_lease = open(dhclient_leases, "r").read() + re_gateway = re.search(fr"option routers {IPREGEX}", dh_lease) + gateway = re_gateway.group().replace("option routers ", "") + else: + rc_conf = open('/etc/rc.conf', 'r').read() + re_gateway = re.search(fr'^defaultrouter="{IPREGEX}"', rc_conf, re.MULTILINE) + if re_gateway: + gateway = re_gateway.group().replace('"', "") + gateway = gateway.replace('defaultrouter=', "") + else: + gateway = "" + + if os.path.exists('/etc/resolv.conf'): + resolv_conf = open('/etc/resolv.conf').read() + nameservers = re.findall(fr'^nameserver {IPREGEX}', str(resolv_conf), re.MULTILINE) + print(nameservers) + + re_domain_search = re.findall('search [a-zA-Z.]*', str(resolv_conf)) + if len(re_domain_search) < 1: + re_domain_search = re.findall('domain (.*)', resolv_conf) + domain_search = str(re_domain_search).replace("domain ", "") + domain_search = domain_search.replace("'", "") + domain_search = domain_search.replace("[", "") + domain_search = domain_search.replace("]", "") + domain_search = domain_search.replace('search', '').strip() + else: + domain_search = '' + nameservers = [] + + interface_settings["Active Interface"] = active_nic + interface_settings["Assignment Method"] = DHCPStatusOutput + interface_settings["Interface IP"] = if_ip + interface_settings["Interface Subnet Mask"] = if_netmask + interface_settings["Broadcast Address"] = if_broadcast + interface_settings["Default Gateway"] = gateway + interface_settings["Search Domain"] = domain_search + + for num in range(len(nameservers)): + interface_settings[ + f"DNS Server {num + 1}" + ] = str(nameservers[(num)]).replace("nameserver", "").strip() + # if DNS Server 1 and 2 are missing create them with empty string + if "DNS Server 1" not in interface_settings: + interface_settings["DNS Server 1"] = "" + if "DNS Server 2" not in interface_settings: + interface_settings["DNS Server 2"] = "" + + return interface_settings diff --git a/setup.py b/setup.py index 70ab69d..9288778 100755 --- a/setup.py +++ b/setup.py @@ -32,9 +32,10 @@ def datafilelist(installbase, sourcebase): ] networkmgr_module = [ + 'NetworkMgr/configuration' 'NetworkMgr/net_api', + 'NetworkMgr/query' 'NetworkMgr/trayicon', - 'NetworkMgr/configuration' ] data_files = [ From 7b9d5af87491a261dc2c905e54c267db29c56ae4 Mon Sep 17 00:00:00 2001 From: ericbsd Date: Fri, 18 Aug 2023 06:59:54 -0300 Subject: [PATCH 24/24] Fixed NetworkMgr module --- NetworkMgr/__init__.py | 0 setup.py | 13 +++---------- 2 files changed, 3 insertions(+), 10 deletions(-) create mode 100644 NetworkMgr/__init__.py diff --git a/NetworkMgr/__init__.py b/NetworkMgr/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/setup.py b/setup.py index 9288778..a362367 100755 --- a/setup.py +++ b/setup.py @@ -31,13 +31,6 @@ def datafilelist(installbase, sourcebase): 'src/setup-nic.py' ] -networkmgr_module = [ - 'NetworkMgr/configuration' - 'NetworkMgr/net_api', - 'NetworkMgr/query' - 'NetworkMgr/trayicon', -] - data_files = [ (f'{prefix}/etc/xdg/autostart', ['src/networkmgr.desktop']), (f'{prefix}/share/networkmgr', networkmgr_share), @@ -54,16 +47,16 @@ def datafilelist(installbase, sourcebase): data_files.extend(datafilelist(f'{prefix}/share/icons/hicolor', 'src/icons')) setup( - name="networkmgr", + name="NetworkMgr", version=PROGRAM_VERSION, - description="Networkmgr is a tool to manage FreeBSD/GHostBSD network", + description="NetworkMgr is a tool to manage FreeBSD/GhostBSD network", license='BSD', author='Eric Turgeon', url='https://github/GhostBSD/networkmgr/', package_dir={'': '.'}, data_files=data_files, install_requires=['setuptools'], - py_modules=networkmgr_module, + packages=['NetworkMgr'], scripts=['networkmgr', 'networkmgr_configuration'] )