Search code examples
pythonsshexpect

Calling `expect` from Python without a separate file


I have the following expect file that I would like to embed in a python script. Currently it is its own separate file that I call from my python script, but I would like to merge the two:

do_remote.sh

#!/usr/bin/expect
spawn ssh -i priv.key user@ip touch test.txt
expect "Enter passphrase for key 'priv.key':"
send "<passphrase>\n"
interact;

call_remote.py

import os
...
os.system('./do_remote.sh')
...

I cannot use any libraries not included with standard python (such as Paramiko or Pexpect).

I do not explicitly need to use the output of the ssh command (but it'd be nice). To be clear, I simply want to only have 1 source code file instead of 2. I am fine with using os.system().


Solution

  • You can specify an Expect script on the command line with expect -c:

    import subprocess
    
    subprocess.call(["expect", "-c", """
        spawn ssh -i priv.key user@ip touch test.txt
        expect "Enter passphrase for key 'priv.key':"
        send "<passphrase>\\n"
        interact;
        """])