1

I am trying to create a solution using Paramiko that allows to grab first line in output with matching criteria. I added while loop to wait until output will be available (some times command will be run for more them an hour). Currently I have:

  1. Connection to jump host
  2. Invoke shell and ssh to second host
  3. Run commands
  4. Wait (using while loop) to required output to be available.
  5. Save it as a str.

But I have problem with breaking while loop after required output is available.

Here is my code.

import paramiko
from time import sleep

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('jumphost', username='User', password='Passw')
sleep(2)
channel = ssh.invoke_shell()
channel.send('ssh secondHost\n')
sleep(2)
channel.send('Command1\n')
#sleep(2)
buff=''

while channel.recv_ready():
    while not buff.endswith('$ '):
        resp = channel.recv(9999)
        for line in resp.split('\n'):
            if line.startswith('Line1'): 
               print(line)
               buff+=line
               break
    break
print 'buff', buff
ssh.close()
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Maksim Ark
  • 25
  • 7

1 Answers1

0

SSHClient.invoke_shell is for implementing an interactive terminal sessions (like if you are implementing your own SSH terminal client), not for automating a command execution. A terminal is a black box with input and output. It does not have any API to execute a command and wait for it to complete.


Use SSHClient.exec_command to execute the command and Channel.recv_exit_status or Channel.exit_status_ready to wait for it to complete.

See Wait until task is completed on Remote Machine through Python.


As you are executing a command within command (Command1 within ssh), you need to send Command1 to the ssh input.

See Execute (sub)commands in secondary shell/command on SSH server in Python Paramiko.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992