Because this question seems to aim somewhere else I am going to point my problem here:
In my python script I am using multiple requests to a remote server using ssh:
def ssh(command):
command = 'ssh SERVER "command"'
output = subprocess.check_output(
command,
stderr=subprocess.STDOUT,
shell=True,
universal_newlines=True
)
return output
here I will get the content of file1 as output.
I have now multiple methods which use this function:
def show_one():
ssh('cat file1')
def show_two():
ssh('cat file2')
def run():
one = show_one()
print(one)
two = show_two()
print(two)
Executing run() will open and close the ssh connection for each show_* method which makes it pretty slow.
Solutions:
- I can put:
Host SERVER
ControlMaster auto
ControlPersist yes
ControlPath ~/.ssh/socket-%r@%h:%p
into my .ssh/config but I would like to solve this within python.
There is the ssh flag
-Tto keep a connection open, and in the before mentioned Question one answer was to use this withPopen()andp.communicate()but it is not possible to get the output between thecommunicatesbecause it throws an errorValueError: Cannot send input after starting communicationI could somehow change my functions to execute a single ssh command like
echo "--show1--"; cat file1; echo "--show2--"; cat file2but this looks hacky to me and I hope there is a better method to just keep the ssh connection open and use it like normal.What I would like to have: For example a pythonic/bashic to do the same as I can configure in the
.ssh/config(see1.) to declare a specific socket for the connection and explicitly open, use, close it