1 minute read

Intro

Dealing with hanging problems in a server closes to magic. If it is a magic, can we detour or fast respond when it happens? To be ready, it is required to have an automated script. In this post, I’m going to write about how to detect the availability of ssh access to servers using a shell script.

Big picture

  1. Implement a shell script
  2. Register using cron
  3. Allow cron to access a full disk
  4. Check up the mail in Mac

1 - Implement a shell script

# enter_ip_addresses, ex) 192.0.0.1 192.0.0.2 ...
for ip in enter_ip_addresses
do
    nc -vz $ip $1 -w 5
    if [ $? == 0 ]
    then
        echo "${ip} ssh is available"
    else
# mail_address_here, ex) abc@abc.com
        echo "${ip} ssh is not available, please contact somebody" | mail -s $ip mail_address_here
    fi
    echo $?
done

Okay, break down the script a little bit. The for-loop iterates a single IP address. The nc command checks up ssh availability to your server and it times out after 5 seconds. If there’s no problem it shows ssh is available, and if not it will send an email using a body message (x.x.x.x ssh is not available, please contact somebody).

2 - Register using cron

crontab -e 

We have to register the execution command using cron. This site helps you to write the cron command. https://crontab.guru/ If you want to check the cron works, you’d better to use short periodic work such as setting it as every minute. (* * * * *)

3 - Allow cron to access a full disk

Here is the thread about allowing access to full disk by cron. https://serverfault.com/a/1012212 If your environment is mac, you need to allow cron to access the disk.

4 - Check up the mail in Mac

mail 

By entering mail in your command-line interface, you can check up results of cron works. If it says “Operation is not permitted”, make sure you allow access to the disk by cron.

Outro

I hope this makes your work automated and I want that you don’t suffer server hang issues. Thanks.

Leave a comment