我正在编写一个脚本,在某个时候需要切换到 root 用户(执行“sudo rootsh”是我们服务器上切换到 root 的唯一可接受的方式),之后它将执行某个命令。
我不确定我遗漏了什么,但是当它应该切换到 root 并继续与启动脚本的用户一起执行命令时,脚本只是忽略了这一部分。
如果检查生成的 whoami.txt
文件,您会注意到用户不是 root。请记住,执行脚本的用户在执行 sudo rootsh 命令时可以毫无问题地切换到 root。
这是我使用的代码:
import subprocess
def switch_user():
commands = '''
sudo rootsh
whoami > whoami.txt
sysctl -a | grep kernel.msgmni'''
process = subprocess.Popen('/bin/bash', stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
out, err = process.communicate(commands.encode('utf-8'))
switch_user()
知道我做错了什么吗?谢谢。
最佳答案
不是 Popen
运行 bash
的子进程,而是 that 打开一个单独的特权 shell,Popen
命令 sudo rootsh
直接。如果成功(要求允许用户 sudo rootsh
无需提供密码),则通过与子进程通信来传递其余命令。
这将是沿着这些思路:
import subprocess
def switch_user():
# These shell commands will be used as input to the root shell
commands = '''whoami > whoami.txt
sysctl -a | grep kernel.msgmni'''
# Launch the root shell
process = subprocess.Popen('/usr/bin/sudo rootsh',
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# Send the shell's input to it and receive back its output
out, err = process.communicate(commands.encode('utf-8'))
switch_user()
您可能需要根据您的目的修改它。特别是,如果您的 sudo
命令位于不同的位置,那么您可能需要修改它的路径。我再次强调,这种方法取决于能够在不提供密码的情况下获得 root shell。 Sudo 可以这样配置,但它不是默认设置。
关于python - 脚本不会切换到另一个用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57380977/