-1

I'm using paramiko to execute commands on another server and most of the time it works fine but for some servers it hangs after executing few commands.

I'd like to know how to troubleshoot and understand the issue.

this is the code I have.

import paramiko 

client = paramiko.SSHClient()
client.set_missing_host_ley_policy(paramiko.AutoAddPolicy)
ssh = client.connect('hostname,username,password')
channel = ssh.invoke_shell()

stdin = channel.makefile('wb')
stdout = channel.makefile('r')


stdin.write(cmd+'\n')
stdin.flush()


#it hangs here
for line in stdout: 
    print(line)
Arman Avetisyan
  • 349
  • 2
  • 10
  • 1) Do not use `invoke_shell` to automate command execution. 2) Do the commands produce any error output? – Martin Prikryl Jun 06 '19 at 05:06
  • How to use stdin and stdout without invoke shell?? No errors at all – Arman Avetisyan Jun 06 '19 at 11:41
  • Show us your code that you use to check for errors + Show us how you execute multiple commands. – Martin Prikryl Jun 06 '19 at 12:33
  • I’m using invoke shell to execute command “bash” with stdin.write(“bash”) and stdin.flush() and then execute second command the same way. I don’t know how to do it without invoke_shell() . I don’t have any specific error handling it’s just stuck when I do stdout.readlines() without displaying any errors – Arman Avetisyan Jun 06 '19 at 14:32
  • OK, so you **do not know** if the commands produce any error output? => read `stderr = channel.makefile_stderr('rb', bufsize) ` – Martin Prikryl Jun 06 '19 at 14:34
  • Strerr hangs the same way on readline . But I’m sure there are no errors with the commands because I’ve executed them manually without any issues. The same script works fine on similar devices but Hangs on some of them. – Arman Avetisyan Jun 06 '19 at 15:21
  • The only way to continue is to close the stdout channel. Stdout.channel.close().. same with stderr. – Arman Avetisyan Jun 06 '19 at 15:27
  • Just because there are no errors when you execute the command manually does not mean there are no errors when you execute the commands in Paramiko. -- Anyway, try calling `set_combine_stderr(True)` before you start reading. – Martin Prikryl Jun 07 '19 at 07:51
  • See [Paramiko ssh die/hang with big output](https://stackoverflow.com/q/31625788/554319). – Martin Prikryl Aug 27 '22 at 17:40

1 Answers1

0

You wrote a for loop to read output of some command which you executed earlier. Is this command continuous running? If yes then you need to read buffer continuously.

Try to write read logic like for line in iter(lambda: stdout.readline(2048), ""): print(line) Because if you don't specify a size, it reads until EOF, that makes the script wait until the command ends before returning from read() and printing any output.
See this : Paramiko, exec_command get the output stream continuously

Chirag Acharya
  • 126
  • 1
  • 12