从 python 中运行需要 root 访问权限的命令
我最近一直在玩子进程。当我做的越来越多;我发现自己需要 root 访问权限。我想知道是否有一种简单的方法可以为需要子进程模块的命令输入 root 密码。因此,当系统提示我输入密码时,我的脚本会提供密码并运行命令。我知道这是一种不好的做法,因为代码的运行位置是沙盒的,并且与系统的其余部分分开;我也不想以 root 身份运行。
如果可能的话,我真的很感激小例子。我知道你可以用expect来做到这一点,但我正在寻找更以Python为中心的东西。我知道 pexpect 存在,但对于这个简单的任务来说有点过大了。
谢谢。
I have been playing around with subprocess lately. As I do more and more; I find myself needing root access. I was wondering if there is an easy way to enter the root password for a command that needs it with subprocess module. So when I am prompted for the password my script and provide it and run the command. I know this is bad practice by where the code will be running is sandboxed and separate from the rest of the system; I also dont want to be running as root.
I would really appreciate small example if possible. I know you can do this with expect, but i am looking something more python centric. I know pexpect
exsists but its a bit overkill for this simple task.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于运行的用户来说,最好利用 sudo Python 程序。您可以指定可以从 sudo 运行而无需密码的特定命令和参数。这是一个例子:
有很多方法,但我更喜欢将命令集分配给组的方法。假设我们想要创建一个组来允许人们以
root
身份运行tcpdump
。因此,我们将该组称为tcpdumpers
。首先,您将创建一个名为
tcpdumpers
的组。然后修改/etc/sudoers
(使用visudo
命令):现在添加到
tcpdumpers
组的任何用户都可以像这样运行 tcpdump:在那里,您可以轻松地将此命令作为
子进程
运行。这样就无需将 root 密码硬编码到程序代码中,并且可以对谁可以在系统上以 root 权限运行什么进行精细控制。
It would probably be best to leverage sudo for the user running the Python program. You can specify specific commands and arguments that can be run from sudo without requiring a password. Here is an example:
There are many approaches but I prefer the one that assigns command sets to groups. So let's say we want to create a group to allow people to run
tcpdump
asroot
. So let's call that grouptcpdumpers
.First you would create a group called
tcpdumpers
. Then modify/etc/sudoers
(using thevisudo
command):Now any user added to the
tcpdumpers
group will be able to run tcpdump like this:From there you could easily run this command as a
subprocess
.This eliminates the need to hard-code the root password into your program code, and it enables granular control over who can run what with root privileges on your system.