Python程序中不使用sudo通过su切换用户执行命令的实现方案
需求与现存问题
- 目标是开发无sudo依赖的Python程序,实现自动完成su用户身份切换、密码校验、指定命令执行,优先基于原生
subprocess模块实现 - 参考目标执行逻辑等价于命令:
su testuser -c id > /tmp/test - 目前自行编写的两套实现均无法正常运行:
原有失效实现
1. 基于subprocess的版本
import subprocess su_password = ("Password\n") proc = subprocess.Popen('su testuser -c id > /tmp/test', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) proc.stdin.write(su_password) proc.stdin.flush()
失效核心原因:
- su命令在绝大多数Linux发行版上默认强制从控制终端读取密码,普通管道的stdin会被su直接忽略,进程直接挂起
- 依赖外层shell处理
> /tmp/test重定向,重定向动作发生在执行su的当前用户上下文,和su切换目标用户后的权限完全错位 - 没有持续读取管道输出,缓冲区写满会直接造成进程死锁,也没有处理退出状态
2. 基于pexpect的版本
import pexpect child = pexpect.spawn('su testuser') child.expect('Password: ') child.sendline('Password123456') child.sendline('id > /tmp/TEST')
失效核心原因:
- 密码输入后没有等待身份校验完成,直接发送执行命令,命令会被su的校验流程直接吞掉
- 没有捕获执行结果与退出状态,密码错误、权限不足等异常没有做兜底处理
可运行实现方案
优先推荐:subprocess原生实现(无第三方依赖)
通过内置的pty模块给su进程分配独立伪终端,绕开su的tty读取限制,全程不需要pexpect这类第三方库:
import os import pty import subprocess import select def run_su_command(target_user: str, su_password: str, exec_command: str, output_file: str): # 为子进程创建独立伪终端 master_fd, slave_fd = pty.openpty() # 拆分su执行参数,不依赖shell解析 su_cmd = ["su", target_user, "-c", exec_command] proc = subprocess.Popen( su_cmd, stdin=slave_fd, stdout=slave_fd, stderr=slave_fd, close_fds=True ) # 父进程关闭slave端,仅保留master端与子进程交互 os.close(slave_fd) output_buffer = b"" password_sent = False while True: # 检测伪终端是否有可读内容 ready, _, _ = select.select([master_fd], [], [], 1) if ready: try: chunk = os.read(master_fd, 1024) if not chunk: break output_buffer += chunk # 检测到su的密码提示时,立即写入校验密码 if b"Password:" in output_buffer and not password_sent: os.write(master_fd, su_password.encode() + b"\n") password_sent = True except OSError: break # 检查子进程是否退出 exit_code = proc.poll() if exit_code is not None: # 读取伪终端剩余未读内容 try: remaining = os.read(master_fd, 4096) output_buffer += remaining except OSError: pass break os.close(master_fd) # 将命令执行输出写入目标文件 with open(output_file, "wb") as f: f.write(output_buffer) return exit_code # 调用示例,等价于目标命令 su testuser -c id > /tmp/test if __name__ == "__main__": run_su_command( target_user="testuser", su_password="替换为testuser的实际密码", exec_command="id", output_file="/tmp/test" )
实现逻辑说明:
- 伪终端完全模拟真实交互终端,su不会触发“必须从终端运行”的报错
- 密码写入时机绑定su的密码提示,不会出现提前发内容被吞的问题
- 输出内容由Python侧统一收集后写入文件,避免shell重定向的权限错位
- 全程捕获进程退出码,可直接判断执行是否成功
备选:修正后的pexpect实现
如果已经引入pexpect依赖,可调整如下逻辑解决原有版本的问题:
import pexpect def run_with_pexpect(target_user: str, su_password: str, exec_command: str, output_file: str): child = pexpect.spawn(f"su {target_user}") # 等待密码提示弹出 child.expect("Password: ") child.sendline(su_password) # 等待su完成身份校验流程 child.expect(pexpect.EOF) # 执行目标命令,重定向输出到目标文件 child.sendline(f"{exec_command} > {output_file}") # 执行完成后退出目标用户shell child.sendline("exit") child.expect(pexpect.EOF) child.close() return child.exitstatus
注意:执行脚本时当前运行的用户不能是root(root运行su无需校验密码),且切换后的目标用户需要对输出文件所在目录有写入权限。
内容的提问来源于stack exchange,提问作者Dimes.U
相关产品推荐
相关产品推荐

