Search code examples
pythonpexpect

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

Solution

  • 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.