Run linux system command as root using python script

I have a postfix installed on my machine, and I update virtual_alias on the fly programmatically (using python) (for some actions). As soon as I update the entry in the / etc / postfix / virtual _alias file, I run the command:

sudo /usr/sbin/postmap /etc/postfix/virtual_alias 2>>/work/postfix_valias_errorfile 
But I get an error message:
 sudo: sorry, you must have a tty to run sudo 

I want to run the indicated sudo command in a non-human way (this means that I am running this system command from a python script.). So how can I run this command programmatically?

+16
python linux root sudo sysadmin
Feb 24 '09 at 19:32
source share
5 answers

You can run your python script as root itself, then you will not need to add privileges to reload the postfix.

Or you can configure sudo to not have a password for /etc/init.d/postfix .

The sudo configuration (via visudo) allows NOPASSWD: allow the command without a password. See http://www.sudo.ws/sudo/man/sudoers.html#nopasswd_and_passwd

 <username> ALL = NOPASSWD: /etc/init.d/postfix 

or something similar.

+19
Feb 24 '09 at 19:39
source share
 #include <unistd.h> #include <stdlib.h> // gcc -o reload_postfix reload_postfix.c // chown root reload_postfix // chmod +s reload_postfix int main( int argc, char **argv ) { setuid( geteuid() ); system("/etc/init.d/postifx reload"); } 

Complete your command in setuid-ed. This will allow any user to restart the postfix. You, of course, can restrict execution permission for certain groups.

+5
Feb 24 '09 at 19:43
source share

To answer the error: "sudo: sorry, you must have tty to run sudo", we have the parameter "Defaults requiretty" in the sudoers file. I tried to comment on this and it worked: D.

+3
Mar 06 '09 at 13:20
source share
 import os os.popen("sudo -S /etc/init.d/postifx reload", 'w').write("yourpassword") 

This, of course, is almost always not a good idea, since the password is in plain text.

+2
Feb 24 '09 at 19:38
source share

if you are going to do this in python, you should just do the following:

write this command before the line you call the shell command

 os.setuid(os.geteuid()) 

then you call the shell command without the prefix "sudo"

0
Feb 17 '13 at 20:46
source share



All Articles