0

I'm sending a command by SSH. This particular command happens to tell the machine to reboot. Unfortunately this hangs my SSH session and does not return so that my script is unable to continue forwards onto other tasks.

I've tried various combinations of modifying the command itself to include "exit" and or escape commands but in none of those cases does the machine pick up on both the reboot and the command to close the SSH session. I've also tried ConnectTimeout and ClientAlive options for SSH but they seem to make the restart command ignored.

Is there some obvious command that I'm missing here?

Milan Novaković
  • 331
  • 8
  • 16

2 Answers2

5

Well, nobody has posted any answers that pertain to SSH specifically, so I'll propose a SIGALRM solution like here: Using module 'subprocess' with timeout

class TimeoutException(Exception): # Custom exception class
  pass

def TimeoutHandler(signum, frame): # Custom signal handler
  raise TimeoutException

# Change the behavior of SIGALRM
OriginalHandler = signal.signal(signal.SIGALRM,TimeoutHandler)

# Start the timer. Once 30 seconds are over, a SIGALRM signal is sent.
signal.alarm(30)

# This try/except loop ensures that you'll catch TimeoutException when it's sent.
try:
  ssh_foo(bar) # Whatever your SSH command is that hangs.
except TimeoutException:
  print "SSH command timed out."

# Reset the alarm stuff.
signal.alarm(0)
signal.signal(signal.SIGALRM, OriginalHandler)

This basically sets a timer for 30 seconds and then tries to execute your code. If it fails to complete before time runs out, a SIGALRM is sent, which we catch and turn into a TimeoutException. That forces you to the except block, where your program can continue.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
TheSoundDefense
  • 6,753
  • 1
  • 30
  • 42
0

I am just going to throw some pseudocode out there, but I would suggest using a flag to denote whether or not you have already rebooted.

File rebootState.py

hasRebooted = False

File sshCommander.py

from rebootState import hasRebooted
if (hasRebooted):
    # Write to rebootState.py "hasRebooted = True"
    # System call to reboot machine
else:
    # Continue execution
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
The2ndSon
  • 307
  • 2
  • 7
  • How will this solve the problem of a SSH command not returning/finishing? – TheSoundDefense Jul 23 '14 at 21:50
  • @TheSoundDefense your right it wont. I was only thinking of a way to track the script's last line of execution. Is the idea here to have one script that runs uninterrupted? – The2ndSon Jul 23 '14 at 21:56
  • @The2ndSon Yes. One script that runs uninterrupted, problem being that the restart of the machine hangs the SSH so it never returns (thus not allowing the script to continue). Side note that since the machine is rebooting, I can't just use "exit" or the such because it's not accepting input. – Milan Novaković Jul 23 '14 at 21:57