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

大兔子大兔子 提交于 2019-11-28 17:58:06

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.

#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.

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.

import os
os.popen("sudo -S /etc/init.d/postifx reload", 'w').write("yourpassword")

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

torkashvan

if you're gonna do this in python you should just do the following:

write this command before the line that you call the shell command

os.setuid(os.geteuid())

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

See StackLick

You need to grant a user to run sudo command without password.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!