1

I have the following code

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
privatekeyfile = 'PK_FILE_PATH'
username ="USERNAME"
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)
client.connect(hostname= IP, username=username, pkey=mykey)
command = SERVER_COMMAND

stdin, stdout, stderr = client.exec_command(command)
while not stdout.channel.exit_status_ready():
  if stdout.channel.recv_ready():
    stdoutLines = stdout.readlines()
print stdoutLines

The command I'm executing takes about 10 seconds to run on the server. It initially returns some information (user profile and module version), then runs some code to check the status of some local server resources.

Paramiko is closing the connection after it receives the initial header information. I need it to wait for the full output of the serverside command to return. I've tried implementing tintin's solution here, with the same result

Any ideas?

Community
  • 1
  • 1
ronald mcdolittle
  • 557
  • 1
  • 7
  • 20

2 Answers2

3

add get_pty=True This will wait until command execution completed. stdin,stdout,stderr = self.ssh.exec_command(command,get_pty=True)

Jeevan Chaitanya
  • 1,255
  • 11
  • 12
  • The `get_pty` is intended for an interactive use. Setting it, when automating command execution, can bring you lot of side effects. Maybe one of the side effects is that the `exec_command` is synchronous (though I doubt it is reliable). But there are definitely lot of other side effects, you do not want, and which can bit you unexpectedly. – Martin Prikryl Mar 29 '21 at 06:06
1

Paramiko is closing the connection after it receives the initial header information.

I do not think that's true. Try running a command like

command = 'echo first && sleep 60 && echo second'
while not stdout.channel.exit_status_ready():
  if stdout.channel.recv_ready():
    stdoutLines = stdout.readlines()
    print stdoutLines

You will get both lines (also note that I'm printing the lines within the loop, so you can see lines).

It must be something with your command, like:

  • The command print the final output on stderr, not stdout.
  • The command does not print the final output when executed without TTY.
  • The command is a script that executes the a sub-command on a background, hence the the script finishes before the sub-command.
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992