我正在开发一个涉及运行一些 sudo 命令的 python 项目。在项目中,我必须运行,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 的情况下运行代码 ie 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
. 嗬!]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句