简体   繁体   English

使用 python 脚本以超级用户身份运行 linux 系统命令

[英]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).我已经在我的机器上安装了 postfix,并且我正在以编程方式(使用 python)(在某些操作上)即时更新 virtual_alias。 Once I update the entry in the /etc/postfix/virtual_alias, I am running the command:更新 /etc/postfix/virtual_alias 中的条目后,我将运行以下命令:

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.).我想以非人为的方式运行提到的 sudo 命令(意思是,我从 python 脚本运行这个系统命令。)。 So how do I get this command run programmatically?那么如何让这个命令以编程方式运行呢?

You can either run your python script as root itself - then you won't need to add privilege to reload postfix.您可以以 root 身份运行 python 脚本 - 然后您无需添加权限即可重新加载后缀。

Or you can configure sudo to not need a password for /etc/init.d/postfix .或者您可以将 sudo 配置为不需要/etc/init.d/postfix的密码。

sudo configuration (via visudo) allows NOPASSWD: to allow the command without a password. sudo 配置(通过 visudo)允许 NOPASSWD: 允许没有密码的命令。 See http://www.sudo.ws/sudo/man/sudoers.html#nopasswd_and_passwdhttp://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.将您的命令包装在 setuid-ed 程序中。 This will let any user restart postfix.这将让任何用户重新启动 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.要回答错误:“sudo:抱歉,您必须有一个 tty 才能运行 sudo”,我们在 sudoers 文件中有一个名为“Defaults requiretty”的设置。 I tried commenting it out and it worked:D.我试着把它评论出来,它奏效了: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.这当然几乎总是不是一个好主意,因为密码是纯文本的。

if you're gonna do this in python you should just do the following:如果您要在 python 中执行此操作,您应该执行以下操作:

write this command before the line that you call the shell command将此命令写在调用 shell 命令的行之前

os.setuid(os.geteuid())

then, you call the shell command without "sudo" prefix然后,您调用不带“sudo”前缀的 shell 命令

See StackLickStackLick

You need to grant a user to run sudo command without password.您需要授予用户在没有密码的情况下运行sudo 命令

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM