Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kpavlovsky/797f487adcf19979a7463916f6b5e329 to your computer and use it in GitHub Desktop.
Save kpavlovsky/797f487adcf19979a7463916f6b5e329 to your computer and use it in GitHub Desktop.
Using paramiko run long running command non blocking with timeout of 60 seconds
import paramiko
import time
from io import StringIO
import sys
import select
def main():
"""Run cat command and tries to cancel it """
ip_address = '52.28.75.66'
with open('/Users/k/.ssh/id_rsa', 'r') as f:
rsa_key = f.read()
username = 'app'
try:
pkey = paramiko.RSAKey.from_private_key(StringIO(rsa_key))
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ip_address, username=username, pkey=pkey, timeout=5)
channel = client.get_transport().open_session()
last_exit_code = -1
start = time.time()
channel.exec_command("docker pull postgres:latest")
while time.time() - start < 60:
if channel.exit_status_ready():
print("received exit_status_ready()")
last_exit_code = channel.recv_exit_status()
break
rl, wl, xl = select.select([channel], [], [], 0.1)
if len(rl) > 0:
print(channel.recv(1024).decode())
time.sleep(0.1)
print(f"last_exit_code: {last_exit_code}")
client.close()
except Exception as e:
return f"Failed {str(e)}"
return "Succeeded"
print(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment