从需要 root 访问权限的 python 中运行命令 [英] Running commands from within python that need root access

查看:105
本文介绍了从需要 root 访问权限的 python 中运行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在玩子进程.随着我做的越来越多;我发现自己需要 root 访问权限.我想知道是否有一种简单的方法可以通过 subprocess 模块为需要它的命令输入 root 密码.所以当我被提示输入密码时,我的脚本并提供它并运行命令.我知道这是一种不好的做法,因为代码将运行在沙盒中并与系统的其余部分分开;我也不想以 root 身份运行.

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.

如果可能的话,我真的很感激小例子.我知道你可以用expect来做到这一点,但我正在寻找更多以python为中心的东西.我知道 pexpect 存在,但对于这个简单的任务来说有点矫枉过正.

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.

谢谢.

推荐答案

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

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:

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

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.

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

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

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

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

% sudo tcpdump 

从那里您可以轻松地将此命令作为 subprocess 运行.

From there you could easily run this command as a subprocess.

这消除了将 root 密码硬编码到您的程序代码中的需要,并且可以精细控制谁可以在您的系统上使用 root 权限运行什么.

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.

这篇关于从需要 root 访问权限的 python 中运行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆