我正在尝试使用conf名称中的vars从python2.7调用logstash命令,我尝试运行的完整shell命令是:
cat test.txt | sudo /usr/share/logstash/bin/logstash -f test.conf
这是我的Python代码:
listname = test
b = '/tmp/%s.txt' % (listname)
c = '/tmp/%s.conf' % (listname)
first = subprocess.Popen(['/bin/echo', b], stdout=subprocess.PIPE)
Second = subprocess.Popen(['/usr/share/logstash/bin/logstash -f', c], stdin=first.stdout)
我无法插入先前在代码中创建的listname变量,我也无法调用logstash。我应该使用shell /子进程来执行此操作还是有更好的方法?
答案 0 :(得分:1)
上面的代码存在许多问题。主要问题可能是您的listname
应该是一个字符串(如果test
不包含字符串),并且您的第二个Popen
调用的语法错误(每个参数应该是它自己的列表条目。)
此外,如果您需要第二个进程使用sudo
,则会出现一些额外问题,具体取决于您是否需要添加密码。
因此,根据如何处理这些问题,您的代码可能看起来像下面的替代方案之一:
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()
希望这有助于您找到合适的解决方案。如果没有,请进一步说明您的问题。