Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep ssh session open after logging in using subprocess.popen?

I am new to Python.

I am trying to SSH to a server to perform some operations. However, before performing the operations, i need to load a profile, which takes 60-90 seconds. After loading the profile, is there a way to keep the SSH session open so that i can perform the operations later?

p = subprocess.Popen("ssh abc@xyz'./profile'", stdout=subprocess.PIPE, shell=True)
result = p.communicate()[0]
print result
return result

This loads the profile and exits. Is there a way to keep the above ssh session open and run some commands?

Example:

 p = subprocess.Popen("ssh abc@xyz'./profile'", stdout=subprocess.PIPE, shell=True)
    <More Python Code>
    <More Python Code>
    <More Python Code>
 <Run some scripts/commands on xyz server non-interactively> 

After loading the profile, I want to run some scripts/commands on the remote server, which I am able to do by simply doing below:

 p = subprocess.Popen("ssh abc@xyz './profile;**<./a.py;etc>**'", stdout=subprocess.PIPE, shell=True)

However, once done, it exists and the next time I want to execute some script on the above server, I need to load the profile again (which takes 60-90 seconds). I am trying to figure out a way where we can create some sort of tunnel (or any other way) where the ssh connection remains open after loading the profile, so that the users don't have to wait 60-90 seconds whenever anything is to be executed.

I don't have access to strip down the profile.

like image 600
Koshur Avatar asked Oct 24 '25 18:10

Koshur


1 Answers

Try an ssh library like asyncssh or spur. Keeping the connection object should keep the session open.

You could send a dummy command like date to prevent the timeout as well.

like image 175
Shanavas M Avatar answered Oct 26 '25 06:10

Shanavas M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!