从需要用户inpu的python运行linux命令

2024-05-29 03:55:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下python代码:

import subprocess
p=subprocess.Popen(["openssl","genrsa","-aes256","-out","ise.key.pem","2048"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
inputdata="123456"
p.communicate(input=inputata)
p.communicate(input=inputata)

以上代码的输出为:

^{pr2}$

我希望输入应该由python提供,不应该有任何用户交互:

我知道证书可以由python pyOpenSSL库生成,但我想使用普通的linux命令

我的python版本是

^{3}$

我看到了下面的链接,但没用

Python execute command line,sending input and reading output

如果在shell中运行该命令,它将按如下方式运行:

pan@pan:~/python-scripts$ openssl genrsa -aes256 -out ise.key.pem 2048
Generating RSA private key, 2048 bit long modulus
..............................................................+++
..+++
e is 65537 (0x10001)
Enter pass phrase for ise.key.pem:
Verifying - Enter pass phrase for ise.key.pem:

Tags: key代码命令inputoutpempanaes256
2条回答

在他的评论中,让-弗朗索瓦·法布雷是对的:

But the real issue is that piping input to a password entering routine doesn't always work.

但不是关于这个:

You have to generate a keyboard event at a lower level.

虽然一般来说这是正确的,但是在当前的情况下,^{}命令向read the password from standard input提供了-passout stdin选项:

openssl genrsa -aes256 -out ise.key.pem -passout stdin 2048

因此,这个Python脚本可以工作:

^{pr2}$

注意,不能多次调用带有timeout=None^{},因为它等待进程终止。但这也不是必需的,因为使用-passout stdin命令不要求验证,因此不需要再次输入密码短语。在

我通常不喜欢这种任务的子进程。。。我更喜欢使用pexpect来模拟人类行为(输入数据。。。等等)。在

这个例子是做这项工作的一个粗略的例子

import pexpect

def main():
        inputdata="123456"
        c = pexpect.spawn("/usr/bin/openssl", ["genrsa","-aes256","-out","ise.key.pem","2048"])
        c.expect("Enter.*:")
        c.sendline(inputdata)
        c.expect("Verifying.*:")
        c.sendline(inputdata)
        c.expect(pexpect.EOF)
        c.close()
        c.kill(0)
        print "Done"

if __name__=='__main__':
        main()

相关问题 更多 >

    热门问题