Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a linux system command as a superuser, using a python script

I have got postfix installed on my machine and I am updating virtual_alias on the fly programmatically(using python)(on some action). Once I update the entry in the /etc/postfix/virtual_alias, I am running the command:

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

I want to run the mentioned sudo command in a non-human way(meaning, I am running this system command from a python script.). So how do I get this command run programmatically?

like image 903
None-da Avatar asked Feb 24 '09 19:02

None-da


3 Answers

You can either run your python script as root itself - then you won't need to add privilege to reload postfix.

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

sudo configuration (via visudo) allows NOPASSWD: to 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.

like image 145
Douglas Leeder Avatar answered Oct 17 '22 14:10

Douglas Leeder


#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");
}

Wrap your command in setuid-ed program. This will let any user restart postfix. You can of course further restrict the execute permission to certain groups.

like image 43
codelogic Avatar answered Oct 17 '22 15:10

codelogic


To answer the error:"sudo: sorry, you must have a tty to run sudo", we have a setting called "Defaults requiretty" in sudoers file. I tried commenting it out and it worked :D.

like image 32
None-da Avatar answered Oct 17 '22 14:10

None-da