Sunday, May 28, 2017

check /etc/hosts by shell script

To practice shell script coding, I coded host check script which ping to hosts wrote in /etc/hosts file and generate check result logs.

1. script

#!/bin/bash

# make directory if unexist
DIR=./pinglog

if [ ! -d $DIR ]; then
mkdir $DIR
echo -e "directory created"
fi

# variables
LOGDIR=$DIR
NOW=$(date +"%Y%m%d-%H%M%S")

OKLOG=$LOGDIR/hostcheck_$NOW.log
NGLOG=$LOGDIR/hostcheck_error_$NOW.log

# check ping reply
while read line; do
hosts=$(echo $line | grep -v ^# | grep -v ^$ | grep -v localhost | cut -d " " -f 2)

# ping to hosts
if [ -n "$hosts" ]; then
ping -c 1 $hosts > /dev/null 2>&1

# it got reply "hostname : OK" else "hostname : NG"
# output OK-log and NG-log file

if [ $? -eq 0 ]; then
echo -e "$hosts : OK" >> $OKLOG
else
echo -e "$hosts : NG" >> $NGLOG
fi
fi
done < /etc/hosts

echo -e "done"
github link is below https://github.com/yoshi-island/shell-script_work/blob/master/check_hosts.sh

2. prepare

In this case, I made active hosts by vagrant on virtualbox. vagrantfile is wrote like this.
VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

  config.vm.define :server do |server|
    server.vm.box = "centos7.0_x64"
    server.vm.hostname = "server"
    server.vm.network :private_network, ip: "192.168.111.223"
    #server.ssh.private_key_path = "~/.ssh/id_rsa"
  end

  config.vm.define :client do |client|
    client.vm.box = "centos7.0_x64"
    client.vm.hostname = "client"
    client.vm.network :private_network, ip: "192.168.111.224"
    #client.ssh.private_key_path = "~/.ssh/id_rsa"
  end

end
start machines on.
% vagrant up

/etc/hosts file is wrote like this.
% cat /etc/hosts | egrep -v "^#"
127.0.0.1    localhost
::1             localhost
192.168.111.223 server  # active on virtualbox
192.168.111.224 client  # active on virtualbox
111.111.111.111 dummy  # dummyhost

3. execute

execute
% bash check_hosts.sh
directory created
done
results
% cat pinglog/hostcheck_20170527-232436.log
server : OK
client : OK
% cat pinglog/hostcheck_error_20170527-232436.log
dummy : NG