在python中运行交互式shell脚本

时间:2015-07-10 09:58:34

标签: python

我有一个shell脚本,我手动执行,如下所示

首先它打印一些消息,然后在最后询问用户名:

>/x/y/somescript "a b c"

Please enter the credentials of the XXX administrator account to use...
NOTE: The account provided below must hold the XXXXX role.

Username:

然后在我输入用户名并按ENTER后,它会要求输入密码

Password: 

输入密码并按ENTER后不久,它会显示一些所需的输出,如下所示。

Following is the list of algorithm(s) available in the system
|  Algorithm Name |      Algorithm Type      | Key Size |  Status  |
|  SHA512withRSA  |   SIGNATURE_ALGORITHM    |    -     | enabled  |
|   SHA1withDSA   |   SIGNATURE_ALGORITHM    |    -     | disabled |
|  SHA256withDSA  |   SIGNATURE_ALGORITHM    |    -     | disabled |
|  SHA512withDSA  |   SIGNATURE_ALGORITHM    |    -     | disabled |
| SHA256withECDSA |   SIGNATURE_ALGORITHM    |    -     | enabled  |

现在我想在python中自动执行此操作。我认为pexpect将是一个很好的工具。我写了一个小脚本。

#!/usr/bin/env python
import pexpect

localcmd='/x/y/some_script "a b c"'

def localOutput(command):
        child = pexpect.spawn (command)
        child.expect ('Username: ')
        child.sendline ('administrator')
        child.expect ('Password: ')
        child.sendline ('Testpassw0rd')
        return child.before   # Print the result of the ls command.

localout=localOutput(localcmd)

print "output from local query: \n "+localout # print out the result

但是当我执行脚本时,它总是说:

# python final.py
output from local query:
 administrator

有人可以告诉我我到底错在哪里吗?

1 个答案:

答案 0 :(得分:0)

pexpect读取子进程的所有输出之前,您的函数可能会过早返回。您需要添加child.expect(pexpect.EOF)以便读取所有输出(可能直到某个缓冲区已满)。

更简单的选择是使用pexpect.run() function

output, status = pexpect.runu(command, withexitstatus=1,
                              events={'Username:': 'administrator\n',
                                      'Password:': 'Testpassw0rd\n'})

如果命令生成大量输出或需要太长时间(timeout参数),则可能会出现问题。