Milad
Milad

Reputation: 5490

Keep SSH connection alive for subsequent ssh command using Python subprocess

I need to regularly make queries to a remote machine in my python program by running shell commands. This is fine using subprocess.run(["ssh", "MY_SERVER", ....]), however I have to access the server by doing multiple ProxyJumps which makes the initial connection establishment very slow.

Is it possible to create a persistent connection to the server first and then issue shell commands and capture stdout through that pipe?

Upvotes: 3

Views: 3644

Answers (1)

Roy2012
Roy2012

Reputation: 12493

There are a couple of ways to do that.

  • Keep the process open. Use Popen to open an ssh process and define its standard input and output as pipes. You can then write to its stdin and read from its stdout. Since you want to do it a number of times, you should not use communicate, but rather write directly to the process stdin using write and flush. (see a piece of same code below)
  • The better solution, in my mind, would be to use a Python ssh package such as https://github.com/paramiko/paramiko/ (or fabric - which is typically used for other purposes). Here, you can open a channel and just write to it and read from it with less hustle.

Sample code for reading / writing to a subprocess

import subprocess

p = subprocess.Popen("bash", stdin=subprocess.PIPE, stdout = subprocess.PIPE, stderr=subprocess.PIPE)

p.stdin.write(b"ls\n")
p.stdin.flush()

res = p.stdout.read(100)
print(res)

Upvotes: 3

Related Questions