如何在Ubuntu中使用python以非root用户身份运行root用户命令

2024-06-14 01:45:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: the项目代码cmdstringbinusrstatus
1条回答
网友
1楼 · 发布于 2024-06-14 01:45:13

@alani对OP的评论是好的,特别是我会尽可能地压制,这样你的节目中的问题就不会产生灾难性的后果。例如,如果您的程序将在组mongo_checkers下运行,则类似这样的操作将启用它只检查状态:

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

这应该是相对无害的

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

相关问题 更多 >