I am getting some discrepancy in the return code below. May be I am not using in the proper way. Every-time I print the return code, it prints the same as the first one has returned. Do I need to reset the return code. I mean in the following example, I am getting the return code as 2 for both the commands. Now when I interchange both the commands, I mean replace ls -al;exit\n with ls -al file_not_exist;exit\n and vice versa, it prints return code 0. Each time it prints the same return code as the first one has returned.

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
ssh.connect('localhost', username='sam', password='mypassword')

channel = ssh.invoke_shell()
channel.send('ls -al file_not_exist;exit\n') #Sending to list a file which doesn't exist
time.sleep(3)
print("My 1st command exit status is: ", channel.exit_status_ready())
print("My 1st command return code is: ", channel.recv_exit_status())

channel.send('ls -al;exit\n')
time.sleep(3)
print("My 2nd command exit status is: ",channel.exit_status_ready())
print("My 2nd command return code is: ",channel.recv_exit_status())

I need to print the return code of each command. Could you please help me in how to get this issue resolved ?

1

There are 1 best solutions below

0
On

The exit status sent back over ssh is that of the remote command execute by the ssh process. You only get one exit status, and in the case of invoke_shell(), that is the exit status of the shell itself. The exit status of commands run within that shell are known only in that environment.

You either need to retrieve and parse the status in the shell or script (the bash shortcut is the variable $?), or execute your commands independently with exec_command().

See also: Can I get the exit code of a command executed in a subshell via ssh?