I've created an expect script that, when executed, ssh's onto a server and executes a series of commands. Pseudocode looks like this:
#!/usr/bin/expect
spawn ssh usr@myip
expect "password:"
send "mypassword\n";
send "./mycommand1\r"
send "./mycommand2\r"
interact
When executed from a bash shell ($ ./myscript.txt) the code executes fine. What I would now like to do is have a line in python file that runs the commands in the script the same way the bash shell does. Pseudocode looks like this:
import subprocess
def runmyscript():
subprocess.call("myscript.txt", executable="expect", shell=True)
def main():
run = runmyscript():
if __name__ == '__main__': main()
I have placed the myscript.txt script file in the same directory as my runmyscript.py file, yet when I run the python file I receive the error:
WindowsError: [Error 2] The system cannot find the file specified
I've read through the documentation on the python.org site, but to no avail. Does anyone have a cunning solution for executing bash scripts from within .py code?
SOLUTION: this code works for me.
child = subprocess.Popen(['bash', '-c', './myscript.txt'], stdout = subprocess.PIPE)
Used this code to call an Expect file to ssh and send commands to server from .py file - useful solution if you are having trouble getting pycrypto/paramiko built onto your machine.
You can use pexpect (http://www.noah.org/wiki/pexpect)
Here is an example function that handles quite a few cases you can run into when executing commands remotely over ssh.
Here is a python implementation of your expect script: