python - sudo/suid 非根嵌套失败

标签 python linux bash python-3.x sudo

我有一个python脚本(必须以root身份调用),它调用一个bash脚本(必须以非root身份调用),有时需要调用sudo。这不起作用 - “叶”sudo 调用给出消息“$user 不在 sudoers 文件中。将报告此事件。”我怎样才能使它工作?

代码(插入您的非根用户名代替“your_username_here”):

测试.py:

#!/usr/bin/python3

import os
import pwd
import subprocess

def run_subshell_as_user(cmd_args, user_name=None, **kwargs):
  cwd = os.getcwd()
  user_obj = pwd.getpwnam(user_name)

  # Set up the child process environment
  new_env = os.environ.copy()
  new_env["PWD"] = cwd
  if user_name is not None:
    new_env["HOME"] = user_obj.pw_dir
    new_env["LOGNAME"] = user_name
    new_env["USER"] = user_name

  # This function is run after the fork and before the exec in the child
  def suid_func():
    os.setgid(user_obj.pw_gid)
    os.setuid(user_obj.pw_uid)

  return subprocess.Popen(
    cmd_args, 
    preexec_fn=suid_func, 
    cwd=cwd,
    env=new_env,
    **kwargs).wait() == 0

run_subshell_as_user(["./tezt"], "your_username_here") # <-- HERE

测试:

#!/bin/bash

sudo ls -la /root

然后运行它:

sudo ./tezt.py

有谁知道为什么这不起作用?用户在正常情况下可以运行sudo。为什么“user -sudo-> root -suid-> user”工作正常,但当您尝试从那里执行 sudo 时却失败了?

最佳答案

我建议使用 sudo 来放弃特权,而不是自己这样做——这在可能的情况下更彻底一些,修改 effective 而不是只修改真实的 uid 和 gid。 (要自己修改完整集,您可以尝试将 setuid() 更改为 setreuid(),同样将 setgid() 更改为 setregid()).

...这意味着将类似于以下内容的内容传递给 Popen:

["sudo", "-u", "your_username_here", "--"] + cmd_args

关于python - sudo/suid 非根嵌套失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38510197/

相关文章:

Python 使用 itertools 查找所有组合/排列(带替换)

python - osx 上的 Tkinter/matplotlib 多个事件窗口

linux - 使用poll()在命名管道上使用O_RDWR

linux - 在linux shell上按文件名长度复制文件

python - 是否可以交替使用 *args 和 **kwargs?

python - Mac 操作系统升级后如何恢复 Python cron 作业?

linux - 目标重新启动时用于 telnet 和 re-telnet 的 Perl 脚本

bash - 根据特定子字符串对 Bash 中的字符串列表进行数字排序

linux - 遍历目录以查找 pom.xml 文件

mysql - 删除 mysql 表数据(Bash 脚本)