Linux Blog

Snippet: Keeping SSH Running

Filed under: Quick Linux Tutorials,Shell Script Sundays — TheLinuxBlog.com at 12:53 am on Sunday, November 4, 2007

I wrote a post not so long back called Bringing The Internet Up After Failure that explained how I was restarting my network services after the internet went down.

Shortly after this I was remotely working when I thought it would be a good idea to restart my SSHD to enable X11 forwarding. After running the script that normally restarts the service I tried to reconnect. Unfortunately the service never restarted after being stopped. This is not a good situation for any one to be in so I added something like this to my cron along at the end of my network services script:

ps ax | grep \usr\/sbin\/sshd | grep Ss && echo "SSHD Running" || echo "Starting SSH"; sudo /etc/rc.d/rc.sshd start

The only difference between the version I am running and the version above is that I don’t echo anything out. All the command does is use the ps command and grep for usr/sbin/sshd then grep for the STAT field of sS. I do this because sshd shows up in the process list as shown below:

owen@the-linux-blog$ ps ax | grep sshd
3463 pts/0    R+     0:00 grep sshd

The rest is self explanitory, it echo’s “SSHD Running” or sudo starts the SSHD.

If SSHD ever terminates on me or those of us who run this snippet we will be able to rightfully regain access to our systems, Hurray!

Man Pages for commands in this post »

ps
grep
echo

2 Comments »

Comment by onegrep

October 28, 2010 @ 10:57 am

you can avoid the two piped grep by using brackets (ex ps aux|grep ss[h]d ) or better , start using monit http://mmonit.com/monit/

Comment by TheLinuxBlog.com

October 28, 2010 @ 11:02 am

Good call. Never heard of monit before, will be worth taking a look at.

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>