0

Can someone let me know how can I reboot a remote server via Python ?

I tried the below command:-

os.system('sudo ssh -q -i /home/support/.ssh/id_rsa_vnera_cluster_keypair -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null support@a.b.c.d "sudo -S su ubuntu -c 'sudo reboot --force'"')

But my code was stuck in the above command waiting for the response as the reboot command does not return anything.

  • OS - Ubuntu 16.04
  • Python 2.7.12
tuk
  • 5,941
  • 14
  • 79
  • 162

1 Answers1

0

2 ideas for you:

  1. Try using nohup in the command string you send the remote server.
  2. Rather than use os.system (which is synchronous) use subprocess.Popen() (which may be used synchronously or asychronously) as follows:
import subprocess as sp

p = sp.Popen(['sudo', 'ssh', '-q' ...])  # complete the list with the rest of your remote command

p.wait()    # if you want to wait.  Can include a timeout in wait().
Ron Kalian
  • 3,280
  • 3
  • 15
  • 23
  • 1
    `nohup` also has the same problem. It is stuck, – tuk Feb 25 '19 at 16:16
  • `subprocess.Popen()` should work then as it is asynchronous (ie returns immediately). If the remote machine subsequently reboots, then that would solve your problem. – Ron Kalian Feb 25 '19 at 16:17
  • https://stackoverflow.com/a/10012262/785523 - I have seen this answer. How can I know if the process ended normally or was timed out ? – tuk Feb 25 '19 at 17:21
  • `status = p.poll()` will return immediately. If `status is None` then process still running. If process has completed, the `status` will be the exit code, 0 if completed OK. – Ron Kalian Feb 25 '19 at 19:34