Reputation: 5490
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
Reputation: 12493
There are a couple of ways to do that.
communicate
, but rather write directly to the process stdin using write
and flush
. (see a piece of same code below)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