在python中运行交互式shell脚本

2024-04-27 08:20:58 发布

您现在位置: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键之后,它会要求输入密码

^{pr2}$

在输入密码并按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

有谁能告诉我我到底哪里错了吗?在


Tags: ofthe脚本child密码usernameaccountalgorithm
1条回答
网友
1楼 · 发布于 2024-04-27 08:20:58

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

更简单的选择是使用^{} function

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

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

相关问题 更多 >