Bits and bytes

SSH service availability using Upstart

Platform: Ubuntu Server

When we access a machine remotely over SSH, we sure do not want its daemon to crash and leave us without the means to access the system. So what we want is some means to make sure that the daemon is immediately restarted in the case of such an unfortunate event. We can easily employ Upstart for this job. Upstart is the recent Ubuntu replacement for the rather aging System V init scripts framework. Its job is basically, as you might expect, to start and stop different services during the startup and shutdown phases.

To make the Upstart manage the SSH daemon start/stop we must first make sure that the deamon is not being managed by the old init compatibility scripts (which is the default setup in Ubuntu 9.04):

localhost ~# update-rc.d -f ssh remove

Now, let’s create the ssh upstart service file:

localhost ~# vim /etc/event.d/ssh

# The Upstart SSH service:

start on runlevel 2
start on runlevel 3
start on runlevel 4
start on runlevel 5

start on runlevel 0
start on runlevel 6

# Let’s forward the daemon output to standard output:
console output

# restart the service in case it crashes, but stop restarting it
# if it continues to crash (i.e., crashes for 3 times in a period of 10 seconds):
respawn
respawn limit 3 10

# the program executable (it shouldn’t be started as a daemon,
# i.e. in the background):
exec /usr/sbin/sshd -D

<CTRL+C>
:w  <ENTER>
:q <ENTER>

That’s it. Now we can use ordinary Upstart commands to manage this service, that is: start ssh, stop ssh and status ssh with their obvious meaning.

At this point we can go to the console and try to kill the daemon process (and, since we haven’t rebooted, shouldn’t forget to start the service first):

localhost ~# start ssh

localhost ~# ps -A | grep -i sshd

123124 ?        00:00:00 sshd

localhost ~# kill -9 123124
localhost ~# ps -A

What we see is that as we locate the ssh daemon and kill it, it soon pops-up on the list of running processes with another pid. That’s what we wanted. And if we are playing with our machine remotely, we shouldn’t be left out in dry when the ssh daemon dies.

# The Upstart SSH service:

start on runlevel 2

start on runlevel 3

start on runlevel 4

start on runlevel 5

start on runlevel 0

start on runlevel 6

# Let’s forward the daemon output to standard output:

console output

# restart the service in case it crashes, but stop restarting it

# if it continues to crash (i.e., crashes for 3 times in a period of 10 seconds):

respawn

respawn limit 3 10

# the program executable (it shouldn’t be started as a daemon,

# i.e. in the background):

exec /usr/sbin/sshd -lkljjlkjklj

<CTRL+C>

:w <ENTER>

:q <ENTER>