如何使用 Ubuntu 中的 python 作为非 root 用户 运行 root 用户命令

How to run root user commands as non root user using python in Ubuntu

我正在从事一个 python 项目,其中涉及 运行 一些 sudo 命令。在项目中,我必须运行、systemctl命令来获取运行ning服务的状态。为此,我有以下代码:

cmd = "sudo service mongodb status > " + status_logs
subprocess.call(cmd, shell=True)
cmd = "grep \'" + search_tag + "\' " + status_logs
status_string = str(subprocess.check_output(cmd, shell=True))

start = status_string.index(":") + len(":")
end = status_string.index(')', start)
status = status_string[start:end]
status = status + ")"
status = status.replace(" ", "")

如果我 运行 上面的代码为 sudo python3 app.py,那么我会得到 active(running)inactive(dead) 的正确响应。但是我需要 运行 没有 sudo 的代码,即 python3 app.py.

在这种情况下,它会不断询问终端中当前用户的密码。我怎样才能删除它并继续进行。请帮忙。谢谢。

/etc/sudoers

的内容
#
# This file MUST be edited with the 'visudo' command as root.
#
# Please consider adding local content in /etc/sudoers.d/ instead of
# directly modifying this file.
#
# See the man page for details on how to write a sudoers file.
#
Defaults        env_reset
Defaults        mail_badpass
Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin: /usr/bin:/sbin:/bin:/snap/bin"

# Host alias specification

# User alias specification

# Cmnd alias specification

# User privilege specification
root    ALL=(ALL:ALL) ALL

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

# See sudoers(5) for more information on "#include" directives:

#includedir /etc/sudoers.d

@alani 对 OP 的评论很好,特别是我会尽可能地压制,这样你的程序问题就不会造成灾难性的后果。例如,如果您的程序将 运行 在组 mongo_checkers 下,这样的事情将启用它只检查状态:

%mongo_checkers ALL= NOPASSWD: /usr/sbin/service mongodb status

这个应该是比较无害的。

[编辑:根据@alani 对此答案的评论,已指定 service 的完整路径。泰!]