简体   繁体   English

python子进程stdin.write(pwd)IOError:[Errno 32]管道损坏

[英]python subprocess stdin.write(pwd) IOError: [Errno 32] Broken pipe

I am trying to write the stdout and stderr to file and input the password for the sudo prompt which is stored in a string. 我正在尝试将stdout和stderr写入文件,并输入存储在字符串中的sudo提示符的密码。 Getting the broken pipe error in the err file when trying to execute it in the background in below way. 尝试以下面的方式在后台执行时,在err文件中获取损坏的管道错误。

cmd.py 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)

pexecutor.py pexecutor.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()

Getting the error: 得到错误:

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

OS : CentOS 操作系统:CentOS

Python Version : 2.7.5 Python版本:2.7.5

For security reasons, sudo reads passwords from the TTY, not from standard input. 出于安全原因,sudo从TTY而非标准输入读取密码。 Try using this command instead: 尝试改用以下命令:

sudo --stdin yum -y install postgresql.x86_64

This will make sudo read the password from standard input, unless requiretty is specified in the sudoers file, in which case you would have to emulate a TTY. 这将使sudo从标准输入中读取密码,除非在sudoers文件中指定了requiretty ,在这种情况下,您将必须模拟TTY。


By the way, note that sudo supports many authentication methods: password is only one of them. 顺便说一下,请注意sudo支持许多身份验证方法:password只是其中一种。 In particular, sudo may not ask for a password (eg, when using NOPASSWD ), so be sure as a minimum to check for the password prompt to be present before writing a password to a process. 特别是,sudo可能不会要求输入密码(例如,在使用NOPASSWD ),因此请确保至少在将密码写入进程之前检查密码提示是否存在。

In general, think about whether offering a program that uses sudo and escalates privileges is something that will make your users happy. 通常,请考虑提供使用sudo并提升特权的程序是否会使您的用户满意。

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

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