Michael Bianconi
Michael Bianconi

Reputation: 5232

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().

Upvotes: 0

Views: 658

Answers (2)

that other guy
that other guy

Reputation: 123460

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;
    """])

Upvotes: 2

inverminx
inverminx

Reputation: 65

That's not really a bash file as the first line on this file:

#!/usr/bin/expect

actually states that the interpreter is expect. Instead of trying to run the shell file from within python, try to launch expect and provide the expect file as the argument:

os.system('/usr/bin/expect do_remote.sh')

Upvotes: -1

Related Questions