问题
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
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/45967099/how-to-automate-shell-interactive-commands-using-python-pexpect-module