0

Im trying to connect via SSH (paramiko) on switches and execute commands to backup the config of it. I saw some similar questions and tried a bunch of them but i didnt find a way to continously read the stdout line after an stdin for my code. I only can read the stdout after i shutdown the stdin with stdin.channel.shutdown_write().

My code looks like this:

import paramiko

def line_buffered(f):
    line_buf = ""
    while not f.channel.exit_status_ready():
        line_buf += f.read(1).decode()
        if line_buf.endswith('\n'):
            yield line_buf
            line_buf = ''

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
client.connect("192.168.18.96", username="admin", password="password")
print("SSH Connection completed.")

stdin, stdout, stderr = client.exec_command('')
print("Start executing...")
stdin.write("something\n")
for line in line_buffered(stdout):
    print(line)
print("-----------------")
print("finished")

stdin.close()
stdout.close()
stderr.close()
client.close()

Output:

SSH Connection completed.
Start executing...


(M4300-52G) >something

              ^

% Invalid input detected at '^' marker.

Still missing the finished

LiiVion
  • 312
  • 1
  • 10
  • See [Paramiko with continuous stdout](https://stackoverflow.com/q/25260088/850848). – Martin Prikryl Jun 13 '22 at 10:17
  • Well if i test it in my code its stops running after i read the stdout with the buffer – LiiVion Jun 13 '22 at 11:38
  • the code above looks like my testing code right now. As i said with this code its getting executed until the `print(line)`. Then its hanging there forever. – LiiVion Jun 13 '22 at 13:23
  • added some more tests into the script (like seen above) – LiiVion Jun 13 '22 at 14:20
  • Well, your tests do not show us that is hangs on `print(line)`. So it more likely hangs in `line_buffered`. What is *"correct"*. You seem to have wrong expectations. See [Execute multiple dependent commands individually with Paramiko and find out when each command finishes](https://stackoverflow.com/q/50962485/850848). – Martin Prikryl Jun 13 '22 at 16:09
  • Thank you! It works with `channel = client.invoke_shell()` and `channel.recv(1024)`. I finally can recieve the shell output. – LiiVion Jun 14 '22 at 15:38

0 Answers0