from subprocess import Popen, PIPE
listname = 'test'
b = '/tmp/{}.txt'.format(listname)
c = '/tmp/{}.conf'.format(listname)
first = Popen(['/bin/cat', b], stdout=PIPE)
# Alt 1, No sudo
second = Popen(['/usr/share/logstash/bin/logstash', '-f', c], stdin=first.stdout)
# Alt 2, sudo with no password
second = Popen(['sudo', '/usr/share/logstash/bin/logstash', '-f', c], stdin=first.stdout)
# Alt 3, add sudo password (most complex)
# Alt 3.1, store password in file (bad)
sudo_password = "clear_text_password"
#Alt 3.2, ask user for password:
from getpass import getpass, getuser
sudo_password = getpass("[sudo] password for {}: ".format(getuser()))
# Since we need to add password at stdin, we cannot directly pipe output from "first"
# instead we set stdin to PIPE, and write sudo password, followed by output from "first"
# sudo -kSp '' ensures that password is read from stdin without prompt being displayed
second = Popen(['sudo', '-kSp', '', '/usr/share/logstash/bin/logstash', '-f', c], stdin=PIPE)
second.stdin.write(sudo_password + '\n') # write password
# followed by output from "first".
for line in first.stdout:
second.stdin.write(line)
second.stdin.close()
上面的代码有很多问题。主要的问题可能是您的
listname
应该是一个字符串(如果test
不包含字符串),并且第二个Popen
调用的语法错误(每个参数都应该是自己的列表项)。在另外,如果您需要第二个进程来使用
sudo
,则会有一些额外的问题,这取决于您是否需要添加密码。在因此,根据如何处理这些问题,您的代码可能看起来像以下备选方案之一:
希望这能帮助你找到一个合适的解决方案。如果没有,请进一步说明您的问题。在
相关问题 更多 >
编程相关推荐