Runing commnad in an interactive remote shell with python and paramiko


/ Published in: Python
Save to your folder(s)

It is necessary on occasion to execute a command in interactive shell. (I needed to to get access to some env vars... ) While there are many way to accomplish this I opted to run my cmd in interactive mode.
To do so I had to write this little wrapper snippet and figured it might be useful for someone else.


Copy this code and paste it in your HTML
  1. def interExecute(host,port,username,password,cmd):
  2. """Execute the given commands in an interactive shell."""
  3. transport = paramiko.Transport((host, port))
  4. transport.connect(username = username, password = password)
  5. chan = paramiko.transport.open_session()
  6. chan.setblocking(0)
  7. chan.invoke_shell()
  8.  
  9. out = ''
  10.  
  11. chan.send(cmd+'\n')
  12.  
  13. tCheck = 0
  14.  
  15. # Wait for it.....
  16. while not chan.recv_ready():
  17. time.sleep(10)
  18. tCheck+=1
  19. if tCheck >= 6:
  20. print 'time out'#TODO: add exeption here
  21. return False
  22. out = chan.recv(1024)
  23.  
  24. return out

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.