2017-06-12 58 views
0

我想寫stdout和stderr文件並輸入存儲在字符串中的sudo提示符的密碼。嘗試在後臺以下面的方式執行它時,在err文件中獲取損壞的管道錯誤。python subprocess stdin.write(pwd)IOError:[Errno 32]損壞的管道

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 

OS:CentOS的

Python版本:2.7.5

回答

0

出於安全原因,sudo從TTY讀取密碼,而不是從標準輸入讀取密碼。嘗試使用這個命令:

sudo --stdin yum -y install postgresql.x86_64 

這將使須藤從標準輸入讀取密碼,除非在sudoers文件,在這種情況下,你將不得不仿效TTY指定requiretty


順便說一下,請注意,sudo支持許多身份驗證方法:密碼只是其中之一。特別是,sudo可能不會要求輸入密碼(例如,在使用NOPASSWD時),因此請確保至少爲,以在將密碼寫入進程之前檢查密碼提示是否存在。

一般來說,考慮提供使用sudo並升級權限的程序是否會讓用戶感到滿意。

相關問題