Hi there,
I am playing with Python so I have an application to start and stop
services as a GUI.
I would prefer not to type sudo python /path/to/script.py as I might as
well just use the command line.
This is just a useful toy to me to help learn a bit about Python. I hope
to add to it down the track.
I tried to use pkexec:
result = subprocess.run(['pkexec', 'systemctl', 'list-unit-files',
'--type=service', '--no-pager', '--plain'], capture_output=True,
text=True, check=True)
...but it just looped and never ran the command.
Any ideas brains trust?
Thanks
P
______________________________
import subprocess
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
def get_systemd_services():
try:
# Run the systemctl command to list all services
result = subprocess.run(['systemctl', 'list-unit-files',
'--type=service', '--no-pager', '--plain'], capture_output=True,
text=True, check=True)
# Split the output into lines
output_lines = result.stdout.splitlines()
# Extract service names and their statuses (enabled or disabled)
services = {}
for line in output_lines[1:]: # Skip the header line
parts = line.split(maxsplit=2) # Split at most 2 parts
if len(parts) >= 2:
services[parts[0]] = parts[1]
return services
except subprocess.CalledProcessError as e:
print(f"Error: {e}")
return None
except Exception as e:
print(f"An error occurred: {e}")
return None
def toggle_service(service, status, checkbox_var):
try:
boot_status = "disabled" if status == 'enabled' else "enabled"
# Invert the checkbox state before toggling
checkbox_var.set(not checkbox_var.get())
# Update the GUI immediately before toggling
update_gui()
if status == 'enabled':
subprocess.run(['sudo', 'systemctl', 'disable', service],
check=True)
subprocess.run(['sudo', 'systemctl', 'stop', service],
check=True) # Stop the service when disabling
message = f"The service {service} has been disabled at boot
and has been stopped"
else:
subprocess.run(['sudo', 'systemctl', 'enable', service],
check=True)
subprocess.run(['sudo', 'systemctl', 'start', service],
check=True) # Start the service when enabling
message = f"The service {service} has been enabled at boot
and has been started"
update_gui()
# Display a pop-up message with corrected status message
messagebox.showinfo("Service Status Update", message)
except subprocess.CalledProcessError as e:
print(f"Error toggling service: {e}")
def update_gui():
# Destroy the previous widgets to refresh the GUI
for widget in frame.winfo_children():
widget.destroy()
services = get_systemd_services()
if services is not None:
# Omit the last line (count of services)
for service, status in list(services.items())[:-1]:
# Use BooleanVar for checkbox default values with
case-insensitive comparison
checkbox_var = tk.BooleanVar(value=status.lower() == 'enabled')
# Include status in the label for testing
checkbox = ttk.Checkbutton(frame, text=service,
variable=checkbox_var, command=lambda s=service, st=status,
var=checkbox_var: toggle_service(s, st, var))
checkbox.pack(anchor='w')
# Create the main window
root = tk.Tk()
root.title("Systemd Services")
# Create a scrollable frame
canvas = tk.Canvas(root)
scroll_y = tk.Scrollbar(root, orient="vertical", command=canvas.yview)
frame = ttk.Frame(canvas)
canvas.create_window((0, 0), window=frame, anchor="nw")
# Update the canvas configuration to enable scrolling
def on_canvas_configure(event):
canvas.configure(scrollregion=canvas.bbox("all"))
canvas.bind("<Configure>", on_canvas_configure)
canvas.configure(yscrollcommand=scroll_y.set)
# Initial update of the GUI
update_gui()
# Add a close button to close the window
close_button = tk.Button(root, text="Close", command=root.destroy)
close_button.pack()
# Pack the canvas and scrollbar
canvas.pack(side="left", fill="both", expand=True)
scroll_y.pack(side="right", fill="y")
# Run the Tkinter event loop
root.mainloop()
_______________________________________________
luv-main mailing list -- [email protected]
To unsubscribe send an email to [email protected]