从 python 中运行需要 root 访问权限的命令

发布于 2024-11-12 05:30:38 字数 281 浏览 4 评论 0原文

我最近一直在玩子进程。当我做的越来越多;我发现自己需要 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最冷一天 2024-11-19 05:30:38

对于运行的用户来说,最好利用 sudo Python 程序。您可以指定可以从 sudo 运行而无需密码的特定命令和参数。这是一个例子:

有很多方法,但我更喜欢将命令集分配给组的方法。假设我们想要创建一个组来允许人们以 root 身份运行 tcpdump。因此,我们将该组称为 tcpdumpers

首先,您将创建一个名为 tcpdumpers 的组。然后修改 /etc/sudoers(使用 visudo 命令):

# Command alias for tcpdump
Cmnd_Alias      TCPDUMP = /usr/sbin/tcpdump

# This is the group that is allowed to run tcpdump as root with no password prompt
%tcpdumpers     ALL=(ALL) NOPASSWD: TCPDUMP

现在添加到 tcpdumpers 组的任何用户都可以像这样运行 tcpdump

% sudo 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 as root. So let's call that group tcpdumpers.

First you would create a group called tcpdumpers. Then modify /etc/sudoers (using the visudo command):

# Command alias for tcpdump
Cmnd_Alias      TCPDUMP = /usr/sbin/tcpdump

# This is the group that is allowed to run tcpdump as root with no password prompt
%tcpdumpers     ALL=(ALL) NOPASSWD: TCPDUMP

Now any user added to the tcpdumpers group will be able to run tcpdump like this:

% sudo tcpdump 

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文