November 19th, 2003, 08:21 AM
Changing users in Python
I'm writing a program (gui, PyGTK), and I need to execute a 'date' command from that program. Of course, 'date' must be ran as root.
So, I guess I'll need to ask the user for the root password (easy enough). But, how do pass that to an su command? Or, is there an easier way to switch users in a python script? I don't want to use sudo, cause I'm not sure that it will be setup on the client PCs. And, I'd prefer not to use xsu (again, cause I'm not sure it will be on the client pcs).
Any help will be appreciated.
November 19th, 2003, 08:43 AM
We'll i'm a little noob boy when it comes to *nix but as for passing your commands all you need is the os.system('command') function to execute simple commands.
I say simple because as soon as you want to get output back from the command line it's much easier to use the commands module!
Just out of interest what does 'date' do?
November 19th, 2003, 08:52 AM
Re: Changing users in Python
It sets the system date and time. Like I said, you need to be root to do it, so simply calling 'date' using os.system won't work.
November 19th, 2003, 09:11 AM
Sorry i got the impression you could pass the root password to the command line to give your user access?
Like i said i'm new to *nix but i'm sure there must be some command that lets the user temp log in as root to preform a restricted comamnd.
On Mandrake linux for example you can access certain restricted things if you enter the root password when prompted too
November 19th, 2003, 10:31 AM
I am fairly sure you can put the 'su' command can be used in the os.command function.
I am looking at some other ways to do this. I'll post back soon.
November 19th, 2003, 11:27 AM
You could use "su -c command" but then you'd need a way of feeding the root password into su on STDIN. There may be a way to do this with more raw access to the shell than system allows, but I don't know of it. That or you could use sudo to simply change the access to date on the user's system.
November 20th, 2003, 10:34 AM
I don't know if you've fond a better way, or already discarded/discovered the method I'm going to propose, but this is how I'm doing it, when I want to execute some python code as root:
You said you didn't know if 'sudo' would be okay, but that's how I use it. 'su' will work as well, though.
if not os.geteuid() == 0:
#os.execlp("sudo", "sudo", *sys.argv)
os.execlp("su", "su", "-c", " ".join(sys.argv))
November 20th, 2003, 10:58 AM
But surely that code requires user input when su is executed before it can complete, for the user to put in the root password?
November 20th, 2003, 06:19 PM
Oh, didn't read that part.
November 21st, 2003, 06:14 AM
So for that reason, I think you either need a way of being more interactive with external commands (there must be a way, surely), or you need to use sudo, which requires doing a little bit of setup work on the user's machine.