简体   繁体   English

在 sudo 中运行 python 文件,但在用户空间中运行配置文件

[英]Run python file in sudo but config file in user space

I wrote a python script that accesses system features which require root privileges.我写了一个 python 脚本来访问需要 root 权限的系统功能。 This "master" script is configured by running another Python script file, "config.py", using exec , that the user of my script would write and which configures some state variables in my script.这个“主”脚本是通过运行另一个 Python 脚本文件“config.py”来配置的,使用exec ,我的脚本的用户会编写它并在我的脚本中配置一些状态变量。

The master script file is root-owned while the config file is user owned (since my script users would want to modify this file).主脚本文件是 root 拥有的,而配置文件是用户拥有的(因为我的脚本用户想要修改这个文件)。

Obviously this is not ideal, since the users of my script could run root-level commands in the config script.显然这并不理想,因为我的脚本的用户可以在配置脚本中运行根级命令。 Is there a way to run the config file in user-level even if the master file was run in root?即使主文件在 root 中运行,有没有办法在用户级别运行配置文件?

What you could do is create a special user to execute the commands that the script users give you.您可以做的是创建一个特殊用户来执行脚本用户给您的命令。 Make sure that this user is locked down to your security requirements dictate.确保此用户已根据您的安全要求进行锁定。

Say that you want this username to be scriptkiddie (for the laughs), then you could create that user in the following way.假设您希望此用户名是scriptkiddie (为了笑),那么您可以通过以下方式创建该用户。

$ useradd scriptkiddie

Then, wrap any system command (here I'll use nmap -Pn -p22 10.0.0.0/8 , a command that requires root ) that your script will execute on behalf of a script user in the runuser command.然后,包装任何系统命令(这里我将使用nmap -Pn -p22 10.0.0.0/8 ,这是一个需要root的命令),您的脚本将在runuser命令中代表脚本用户执行。

runuser will run whatever you give it in the context of whatever user you specify. runuser将在您指定的任何用户的上下文中运行您提供的任何内容。

$ runuser -l  scriptkiddie -c 'nmap -Pn -p22 10.0.0.0/8'

In Python you could use format(...) to inject whatever command is given to you.在 Python 中,您可以使用format(...)来注入给您的任何命令。

"runuser -l  scriptkiddie -c {}".format(user_cmd)

This method will prevent any user being able to run a command in the context of root , since all commands will be run under the context of the new user scriptkiddie .此方法将阻止任何用户能够在root的上下文中运行命令,因为所有命令都将在新用户scriptkiddie的上下文中运行。

Since it's a config file, you might be better off making it something non-executable like a plain ini / yaml etc. I'm assuming you want to include it to access some constants.由于它是一个配置文件,因此最好将其设置为不可执行的文件,例如普通的 ini / yaml 等。我假设您希望包含它以访问某些常量。 Sometimes it requires a little more work to set up, but ultimately, if the only code that runs is yours, you can be safe(er).有时它需要更多的工作来设置,但最终,如果唯一运行的代码是你的,你就可以安全(呃)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM