简体   繁体   中英

How to automate shell interactive commands using Python pexpect module

I am trying to automate the setup of an application by performing SSH to the machine and goto /var/packages folder and execute the script.when the installation starts a set of interactive commands to be send based on the expected output.I found from google that pexpect can achieve this but i am unable to achieve the result that i wish. I am trying following code , can someone guide me how to achieve this as I am beginner to python.Any help would be appreciated. My application setup would look like this

[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 Code

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

You're on the right track with using the s.before log for debugging.

The app you're interacting with appears to be more screen-oriented than line-oriented, which can pose some difficulties, including ANSI escape sequences for color and position. Consider running child.expect('Something else') , some string which does reliably show up in before , then do a brief sleep() , then just "blindly" send "2" or "y" or whatever, pausing briefly between sends.

You should change

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

to

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

spawn is supposed to run a program on the local host, not on the remote host.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM