Search code examples
pythonuser-interfacewxpythonrootwxwidgets

wxPython - Getting root sudo access and handling root access


I have a GUI that sets up everything needed for a simulation. The thing is, the simulation is using linux containers and namespaces and I need root access to set up the simulation. Right now, I can run my gui.py as root with sudo and all is well, but I would like to be able to run it as any user. When root access is needed, a prompt would then ask for the password. Other applications do it all the time. Can this be done easily with wx? Once I have root access, how will I then distinguish between what is being done as root and what is not?


Solution

  • root_pw = wx.GetTextFromUser("Enter Root Password:")
    os.system("echo {pw} | sudo -S -p '' {root_cmd}".format(pw=root_pw,root_cmd="apt-get install something"))
    

    (really you probably want to use one of the mechanisms other than os.system)

    is one way you could easily do this ...

    this leverages the -S switch that tells sudo to use the next thing provided to STDIN as the root password rather than prompt for it ... echoing the password then provides the password

    if your root stuff is python you could make a second .py that is called require_root.py or something and call that with the above method

    alternatively you could give it "python {my_name}".format(my_name=sys.argv[1]) as the command and then destroy your current frame effectivly relaunching the application with root privledges

    I would recommend just checking if you have root privledges before launching and if you dont propmt for them as shown above and launch your main_app.py script as sudo (or just print that they need to run as root (or show wx.MessageBox or whatever)