Start interactive SSH session from Python script

Question:

I’d like to start an interactive SSH terminal from a Python script without using modules like pexpect or paramiko – I want to stick with what CentOS pre-installed Python provides me (to ease compatibility and deployment issues).

I can run commands fine using the subprocess module, but cannot get an interactive terminal. In Perl, I would just use backticks to achieve this, but am looking for the pythonic way of doing this.

Can someone point me in the right direction?

UPDATE – based on @leoluk’s answer, I used the instructions from docs.python.org to come up with: subprocess.call("ssh ...", shell=True)

Asked By: sholsapp

||

Answers:

I get an interactive terminal if I use os.system('ssh [...]')

Answered By: leoluk

You could use pexpext if you want to mix interaction with automatic response

http://www.noah.org/wiki/Pexpect

Answered By: Falmarri

For clarity and simplicity for future visitors of this thread, here is an example using the OP’s subproccess.popen() solution.

try:
     print("Starting SSH connection...")
     ssh_cmd = 'ssh -vvv -i your_ssh_key -o BatchMode=yes -p 22 user@server_address 2> ssh-error.log'
     subprocess.run(ssh_cmd, shell=True)

except subprocess.CalledProcessError as e:
     raise SystemExit(e)
Answered By: Rex Linder
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.