Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing reboot command over SSH using Paramiko

I use Paramiko for establishing SSH connection with some target device and I want to execute reboot command.

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(zip_hostname, username=username, password=password, timeout=1)
try:
    stdin, stdout, stderr = ssh.exec_command("/sbin/reboot -f")
    # .........
    # some code
    # .........
except AuthenticationException, e:
    print ''
finally:
    ssh.close()

But after executing ssh.exec_command("/sbin/reboot -f") "some code" does not execute because program is stuck in exec_command (the disconnection takes place caused by rebooting). What should I do to solve my problem?

like image 478
Mind Mixer Avatar asked Jul 20 '26 11:07

Mind Mixer


2 Answers

Try this:

ssh.exec_command("/sbin/reboot -f > /dev/null 2>&1 &")

All the output of reboot is redirected to /dev/null to make it produce no output and it is started in the background thanks to the '&' sign in the end. Hopefully the program won't hang on that line this way, because the remote shell gives the prompt back.

like image 150
Géza Török Avatar answered Jul 22 '26 00:07

Géza Török


All you need to do is to call channel.exec_command() instead of the high-level interface client.exec_command()

# exec fire and forget
timeout=0.5
transport = ssh.get_transport()
chan = ssh.get_transport().open_session(timeout=timeout)
chan.settimeout(timeout)
try:
  chan.exec_command(command)
except socket.timeout:
  pass
like image 40
tintin Avatar answered Jul 22 '26 00:07

tintin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!