Starting sshd automatically if it is down/failed

I am trying to create a Bash .sh script for a cronjob that starts the OpenSSH server if it is down or failed.

Last night the SSH server was down and when I tried to access it today (from work) the connection was refused ofc. No traces in the /var/log/messages for the failure.

So the question is - how to determine is sshd running so if it is not to "sudo service ssh start" it?

Thanks in advance!

Upvotes: 1

Views: 2497

Answers (3)

geotheory
geotheory

Reputation: 23670

I'm implementing the following:

[ $(sudo service ssh status | grep running | grep -v grep | wc -l) == 0 ] && sudo /etc/init.d/ssh restart

Upvotes: 2

Fellas, I believe that I have managed to do the task:

#!/bin/bash
service="ssh"

if (( ! $(sudo service ssh status | cut -d" " -f 3 | cut -d"." -f 1) == "running" ))
then
        sudo /etc/init.d/ssh restart
fi

I have changed the LogLevel to Verbose, I hope the next time I will track more clues regarding the failure of the sshd.

Upvotes: 4

Fattaneh Talebi
Fattaneh Talebi

Reputation: 767

as other people said It's Incorrect to start it without finding what caused this problem, but I wrote some help for the script you want

  1. first you should check the status of your openssh server for example:

ps -aux | grep ssh

  1. then write an if to check if it is down or not

    you can check it with the result of previous step.

  2. if that was down, start it

sudo service ssh start

Upvotes: 0

Related Questions