如何使用 Python pexpect 模块自动化 shell 交互式命令

How to automate shell interactive commands using Python pexpect module

我正在尝试通过对机器执行 SSH 并转到 /var/packages 文件夹并执行 script.when 来自动设置应用程序,安装会启动一组要发送的交互式命令预期的 output.I 从 google 中发现 pexpect 可以实现这一点,但我无法实现我希望的结果。我正在尝试遵循代码,有人可以指导我如何实现这一点,因为我是初学者 python.Any 帮助将不胜感激。我的应用程序设置如下所示

[root@bits packages]# ./SHR_setup.bin -i console
    Preparing to install...
    Extracting the JRE from the installer archive...
    Unpacking the JRE...
    Extracting the installation resources from the installer archive...
    Configuring the installer for this system's environment...

    Launching installer...

    ===============================================================================
    Choose Locale...
    ----------------

        1- Deutsch
      ->2- English
        3- Español
        4- Français
        5- Italiano
        6- Nederlands
        7- Português  (Brasil)

    CHOOSE LOCALE BY NUMBER: 2
    I accept the terms of the License Agreement (Y/N): Y
    Please hit Enter to continue:

Python代码

from pexpect import pxssh
import pexpect

    try:
        s = pxssh.pxssh()
        hostname = '10.110.40.20'
        username = 'admin'
        password = 'admin123'
        s.login(hostname, username, password)
        s.sendline('cd /var/packages')   # goto /var/packages folder
        child = pexpect.spawn('./SHR_setup.bin -i console')  # start the application setup in packages folder
        child.expect('CHOOSE LOCALE BY NUMBER')   # expect output like this 
        child.sendline('2')   
        s.prompt()
        print s.before
    except pxssh.ExceptionPxssh, e:
        print 'pxssh failed on login'
        print e

您使用 s.before 日志进行调试的方向正确。

您正在与之交互的应用程序似乎更面向屏幕而不是面向行,这可能会带来一些困难,包括用于颜色和位置的 ANSI 转义序列。考虑 运行 child.expect('Something else')确实 可靠地出现在 before 中的一些字符串,然后做一个简短的 sleep(),然后只是 "blindly" 发送 "2" 或 "y" 或其他,在发送之间短暂暂停。

你应该改变

s.sendline('cd /var/packages')
child = pexpect.spawn('./SHR_setup.bin -i console')

s.sendline('cd /var/packages')
s.sendline('./SHR_setup.bin -i console')

spawn 应该是 运行 local 主机上的程序,而不是 remote 主机上的程序.