ronald mcdolittle
ronald mcdolittle

Reputation: 567

Python Paramiko - wait on more output from passed command before exiting

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?

Upvotes: 1

Views: 4592

Answers (2)

Jeevan Chaitanya
Jeevan Chaitanya

Reputation: 1384

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

Upvotes: 3

Martin Prikryl
Martin Prikryl

Reputation: 202232

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.

Upvotes: 1

Related Questions