【问题标题】:python subprocess stdin.write(pwd) IOError: [Errno 32] Broken pipepython subprocess stdin.write(pwd) IOError: [Errno 32] Broken pipe
【发布时间】:2017-06-12 09:42:30
【问题描述】:

我正在尝试将 stdout 和 stderr 写入文件并输入存储在字符串中的 sudo 提示的密码。尝试以下列方式在后台执行时,在 err 文件中出现损坏的管道错误。

cmd.py

def preexec_function():
    import os
    import signal
    # Detaching from the parent process group
    os.setpgrp()
    # Explicitly ignoring signals in the child process
    signal.signal(signal.SIGINT, signal.SIG_IGN)

cmd = "python pexecutor.py"
p = Popen(cmd, close_fds=True, stdout=None, stderr=None, stdin=None,
          preexec_fn=preexec_function)

执行程序.py

from subprocess import Popen, PIPE
import os
command="sudo yum -y install postgresql.x86_64"
stdin_str="myrootpwd"
std_out_file = open("out.txt", 'a+')
std_err_file = open("err.txt", 'a+')
process = Popen(command, stdout=std_out_file, stderr=std_err_file, 
                stdin=PIPE)
import time
time.sleep(5)
pwd = b'{}'.format(stdin_str + str(os.linesep))
process.stdin.write(pwd)
process.stdin.flush()
data = process.communicate()

得到错误:

Traceback (most recent call last):
    File "pexecutor.py", line 10, in execute
  process.stdin.write(pwd)
IOError: [Errno 32] Broken pipe

操作系统:CentOS

Python 版本:2.7.5

【问题讨论】:

    标签: python subprocess ioerror


    【解决方案1】:

    出于安全原因,sudo 从 TTY 而非标准输入读取密码。尝试改用这个命令:

    sudo --stdin yum -y install postgresql.x86_64
    

    这将使 sudo 从标准输入中读取密码,除非在 sudoers 文件中指定了 requiretty,在这种情况下您必须模拟 TTY。


    顺便请注意,sudo 支持多种身份验证方法:密码只是其中一种。特别是,sudo 可能不会要求输入密码(例如,当使用 NOPASSWD 时),因此请确保至少在将密码写入进程之前检查是否存在密码提示。

    一般来说,考虑提供一个使用 sudo 并提升权限的程序是否会让您的用户满意。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-24
      • 2016-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      相关资源
      最近更新 更多