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?

0

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.