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?
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!
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.
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.
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.
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:
(For Windows, there is an alternative to pexpect.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With