Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to run an Expect script from Python

I'm trying to instruct my Python installation to execute an Expect script "myexpect.sh":

#!/usr/bin/expect
spawn ssh usr@myip
expect "password:"
send "mypassword\n";
send "./mycommand1\r"
send "./mycommand2\r"
interact

I'm on Windows so re-writing the lines in the Expect script into Python are not an option. Any suggestions? Is there anything that can run it the way "./myexpect.sh" does from a bash shell?


I have had some success with the subprocess command:

subprocess.call("myexpect.sh",  shell=True)

I receive the error:

myexpect.sh is not a valid Win32 application.

How do I get around this?

like image 384
gortron Avatar asked Jun 22 '12 16:06

gortron


People also ask

How do I run a Python script?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!

How do I run a shell script in Python?

If you need to execute a shell command with Python, there are two ways. You can either use the subprocess module or the RunShellCommand() function. The first option is easier to run one line of code and then exit, but it isn't as flexible when using arguments or producing text output.

What does expect do in Python?

Pexpect is a Python module for spawning child applications and controlling them automatically. Pexpect can be used for automating interactive applications such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup scripts for duplicating software package installations on different servers.

How do I run a Python file in terminal?

To run the script from the command line simply type python followed by the path to the file. For example, if the helloworld.py file was located in the directory C:/temp , you would type python C:/temp/helloworld.py and press 'Enter'. The text in the file will now print to the command prompt/terminal.


1 Answers

Use the pexpect library. This is the Python version for Expect functionality.

Example:

child = pexpect.spawn('Some command that requires password')
child.expect('Enter password:')
child.sendline('password')
child.expect(pexpect.EOF, timeout=None)
cmd_show_data = child.before
cmd_output = cmd_show_data.split('\r\n')
for data in cmd_output:
    print data

Pexpect comes with lots of examples to learn from. For use of interact(), check out script.py from examples:

  • https://github.com/pexpect/pexpect/tree/master/examples

(For Windows, there is an alternative to pexpect.)

  • Can I use Expect on Windows without installing Cygwin?
like image 191
pyfunc Avatar answered Sep 18 '22 07:09

pyfunc