Wait until task is completed on Remote Machine through Python

Irfan Ghaffar7 picture Irfan Ghaffar7 · Feb 12, 2015 · Viewed 21.8k times · Source

I am writing a program in python on Ubuntu. In that program I am trying to print a message after completing a task "Delete a File" on Remote machine (RaspberryPi), connected to network.

But In actual practice, print command is not waiting till completion of task on remote machine.

Can anybody guide me on how do I do that? My Coding is given below

import paramiko

# Connection with remote machine
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.2.34', username='pi', password='raspberry')

filename   = 'fahad.txt'
filedelete ='rm ' + filename
stdin, stdout, stderr = client.exec_command(filedelete)
print ("File Deleted")
client.close()

Answer

Sylvain Leroux picture Sylvain Leroux · Feb 12, 2015

This is indeed a duplicate of paramiko SSH exec_command(shell script) returns before completion, but the answer there is not terribly detailed. So...

As you noticed, exec_command is a non-blocking call. So you have to wait for completion of the remote command by using either:

  • Channel.exit_status_ready if you want a non-blocking check of the command completion (i.e.: pooling)
  • Channel.recv_exit_status if you want to block until the command completion (and get back the exit status — an exit status of 0 means normal completion).

In your particular case, you need the later:

stdin, stdout, stderr = client.exec_command(filedelete)  # Non-blocking call
exit_status = stdout.channel.recv_exit_status()          # Blocking call
if exit_status == 0:
    print ("File Deleted")
else:
    print("Error", exit_status)
client.close()