[英]python subprocess stdin.write(pwd) IOError: [Errno 32] Broken pipe
我正在尝试将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)
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()
得到错误:
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
出于安全原因,sudo从TTY而非标准输入读取密码。 尝试改用以下命令:
sudo --stdin yum -y install postgresql.x86_64
这将使sudo从标准输入中读取密码,除非在sudoers文件中指定了requiretty
,在这种情况下,您将必须模拟TTY。
顺便说一下,请注意sudo支持许多身份验证方法:password只是其中一种。 特别是,sudo可能不会要求输入密码(例如,在使用NOPASSWD
),因此请确保至少在将密码写入进程之前检查密码提示是否存在。
通常,请考虑提供使用sudo并提升特权的程序是否会使您的用户满意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.