简体   繁体   中英

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. Getting the broken pipe error in the err file when trying to execute it in the background in below way.

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

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

Python Version : 2.7.5

For security reasons, sudo reads passwords from the TTY, not from standard input. 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.


By the way, note that sudo supports many authentication methods: password is only one of them. 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.

In general, think about whether offering a program that uses sudo and escalates privileges is something that will make your users happy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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