3

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?

1
  • Another option: if the commands you need to run are repetitive, store them on the remote server as shell scripts, and then call them directly. Commented Jun 22, 2020 at 1:32

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.