1

I'm executing gcloud command inside the remote host. However, when I try to execute any command using the ssh.exec_command, the command seems to get executed. But how can I make sure it executed correctly.

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname = HOSTNAME,username = USERNAME,key_filename = FILENAME)
firewall_list = [gke-cluster-XXX-all,gke-cluster-XXX-ssh,gke-cluster-XXX-vms]
cmd = 'gcloud compute firewall-rules delete'+firewall_list
stdin,stdout,stderr = ssh.exec_command(cmd)
ssh.close()

How can I check ssh.exec_command executed successfully?

Thanks

Pepper
  • 65
  • 1
  • 8

1 Answers1

1

There are a couple of ways, but generally speaking, you should just evaluate the exit code for the command being executed using:

stdout.channel.recv_exit_status()

Note that this will only work for brief output or quick commands as Martin Prikryl mentioned, otherwise it will deadlock.

Depending on the command being executed, you can either check for a zero exit code or rule out specific exit codes depending on the command.

cmd = 'gcloud compute firewall-rules delete'+firewall_list
stdin,stdout,stderr = ssh.exec_command(cmd)
# Verify this condition applies to your specific case
if stdout.channel.recv_exit_status() != 0:
   # error handling, your command was not succesful
ssh.close()

Although not preferred, you can also verify the contents of readlines() or read() on stdout and stderr, but this is often not necessary.

  • 2
    While you are correct about `recv_exit_status`, you cannot use it this way, as the code may deadlock. You have to consume the command output, while waiting for the command to finish. See [Paramiko ssh die/hang with big output](https://stackoverflow.com/q/31625788/850848). – Martin Prikryl Aug 19 '20 at 16:46