Bash ping status script - bash

I've done the following script
HOSTS="ns1.server.com ns2.server.com"
SUBJECT="Host Down"
for myHost in $HOSTS
do
count=$(ping -c 10 $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{
print $1 }')
if [ $count -eq 0 ]; then
echo "Host : $myHost is down (ping failed) at $(date)" | sendEmail -f email (email address removed) -u "$SUBJECT" etc etc
fi
done
Run via cron every 5 minutes however when a host is down I will receive and email every 5 minutes reflecting this. What i'd like is to add the function so that it only emails me when the status has changed. ie if it's down I don't want it to send any further updates until it's up.

I think something like this can help:
#!/bin/bash
HOSTS="ns1.server.com ns2.server.com"
HOSTS="123.123.1.1 ns1.server.com"
SUBJECT="Host Down"
ping_attempts=1
down_hosts=down_hosts.txt
for myHost in $HOSTS
do
count=$(ping -c $ping_attempts $myHost | awk -F, '/received/{print $2*1}')
echo $count
if [ $count -eq 0 ]; then
echo "$myHost is down"
if [ $(grep -c "$myHost" "$down_hosts") -eq 0 ]; then
echo "Host : $myHost is down (ping failed) at $(date)"
echo "$myHost" >> $down_hosts
fi
else
echo "$myHost is alive"
if [ $(grep -c "$myHost" "$down_hosts") -eq 1 ]; then
echo "Host : $myHost is up (ping ok) at $(date)"
sed -i "/$myHost/d" "$down_hosts"
fi
fi
done

There is a good point in the comments that you might want to use an infinite loop. But as you have asked for something different, here you go:
HOSTS="ns1.server.com ns2.server.com"
SUBJECT="Host Down"
PATH_STATUS='/yourfolder/hoststatus_' # For example can be located in /tmp.
for myHost in $HOSTS; do
count=$(ping -c 10 "$myHost" | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
[[ -f "$PATH_STATUS$myHost"]] && prevStatus=$(cat "$PATH_STATUS$myHost") || prevStatus='unknown'
[[ $count == 0 ]] && curStatus='down' || curStatus='up'
if [[ $curStatus != $prevStatus ]]; then
echo "$curStatus" > "$PATH_STATUS$myHost"
echo "Host : $myHost is $curStatus at $(date)" | sendEmail
fi
done

Related

pb nagios bash script null result in if

I have a problem with a bash script in Nagios. this is a script to get the space disk. When I used an IF section it returns (null) and when I don't set the variable in IF section, nagios display the variable correctly. I tried to run the script with nagios user and the result is good. Ex:
TOTAL=`/srv/eyesofnetwork/nagios/plugins/check_nt -H $2 -p 12489 -s "" -v USEDDISKSPACE -l $4 |awk -F"-" '{print $2}' |awk '{print $2}'`
if [ $TOTAL -gt 2 ] && [ $TOTAL -le 99 ];then
RUN=`/srv/eyesofnetwork/nagios/plugins/check_nrpe -H $2 -c ``check_drivesize -a drive=$4 'warning=free<2G' 'critical=free<1G' show-all 'perf-config=*(unit:G)' top-syntax='${status} : ${problem_list}'`
VAR=$(echo $RUN |grep -i ok |wc -l)
if [ $VAR -eq 1 ];then
echo "$RUN"
exit 0
fi
I tried all possibilities (for me..), with "", with '', with nothing. The variable $RUN is not displayed.
Thanks
Finally, I wrote a script in python and now it works correctly

Email Alerts when service or server automatically comes up

I am working on a bash script that helps to ping and get the network interface level status of the host machines and services.
This script will send a email alerts in case of failure.
#!/bin/bash
HOSTS="192.168.8.200"
COUNT=4
for myHost in $HOSTS
do
count=$(ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
if [ $count -eq 0 ]; then
# 100% failed
echo -e "HOST:$myHost is down (ping failed) at $(date)" | mailx -A gmail -s “Mail subject” anymail#anydomain.com
fi
done
This works fine.
But need help to get a one single email alert when host automatically comes up (ping success).
You need to save the state of the host (up/down) during the calls of your script.
if the host is "up" and the former state was "down" then you need to send an email.
You can just write the result of the "check command" to a file in /tmp/
if the check returns that the server is up you read the content of the file. if the state is "down" in the file, then send an email an write "up" to the file.
on the next check if the server is up, there will be no additional email sent, because the server was also "up" before.
#!/bin/bash
HOSTS="192.168.8.200 192.168.8.201 192.168.122.1"
COUNT=4
STATE="/tmp/ping_state.txt"
for myHost in $HOSTS
do
count=$(ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
if [ $count -eq 0 ]; then
# 100% failed
#echo -e "HOST:$myHost is down (ping failed) at $(date)" | mailx -A gmail -s “Mail subject” anymail#anydomain.com
echo "host $myHost down"
#delete all previous entries of that ip
sed -i "/$myHost/d" $STATE
#mark host as down
echo "$myHost - down" >> $STATE
else
CHECK=`grep "$myHost" $STATE | grep -o "down"`
if [ "$CHECK" = "down" ]; then
echo "host $myHost up again"
#insert email for host up here
fi
#delete all previous entries of that ip
sed -i "/$myHost/d" $STATE
echo "$myHost - up" >> $STATE
fi
done
for simple testing I just used an echo statement instead of sending an email.

if statement function to many argumnets

I've overlooked my program for any mistakes and can't find any. Usually when I run into a mistake with BASH the interpreter is off on where the mistake is. I'm trying to customize this script from SANS InfoSec Using Linux Scripts to Monitor Security. Everything is fine until the part where the check function looks at the different protocols. When I uncomment them I get the error: ./report: line 41: [: too many arguments. Here is the program...
#!/bin/bash
if [ "$(id -u)" != "0" ]; then
echo "Must be root to run this script!"
exit 1
fi
##### CONSTANTS -
report=/home/chron/Desktop/report.log
#router=/home/chron/Desktop/router.log
red=`tput bold;tput setaf 1`
yellow=`tput bold;tput setaf 3`
green=`tput bold;tput setaf 2`
blue=`tput bold;tput setaf 4`
magenta=`tput bold;tput setaf 5`
cyan=`tput bold;tput setaf 6`
white=`tput sgr0`
##### FUNCTIONS -
pingtest() {
ping=`ping -c 3 localhost | tail -2`
loss=`echo $ping | cut -d"," -f3 | cut -d" " -f2`
delay=`echo $ping | cut -d"=" -f2 | cut -d"." -f1`
if [ "$loss" = "100%" ]; then
echo -n $red$1$white is not responding at all | mail -s'REPORT' localhost
echo 'You have mail in /var/mail!'
echo `date` $1 is not responding at all >> $report
elif [ "$loss" != "0%" ]; then
echo $yellow$1$white is responding with some packet loss
else
if [ "$delay" -lt 100 ]; then
echo $green$1$white is responding normally
else
echo $yellow$1$white is responding slow
fi
fi
}
check() {
if [ "$2" != "" -a "$2" $3 ] ; then
echo -n $green$1$white' '
else
echo -n $red$1$white' '
echo `date` $1 was not $3 >> $report
fi
}
##### __MAIN__ -
pingtest localhost # hostname or ip
echo "Server Configuration:"
check hostname `hostname -s` '= localhost'
check domain `hostname -d` '= domain.com'
check ipaddress `hostname -I | cut -d" " -f1` '= 10.10.0.6'
check gateway `netstat -nr | grep ^0.0.0.0 | cut -c17-27` '= 10.10.0.1'
echo
echo "Integrity of Files:"
check hostsfile `md5sum /etc/hosts | grep 7c5c6678160fc706533dc46b95f06675 | wc -l` '= 1'
check passwd `md5sum /etc/passwd | grep adf5a9f5a9a70759aef4332cf2382944 | wc -l` '= 1'
#/etc/inetd.conf is missing...
echo
#echo "Integrity of Website:"
#check www/index.html `lynx -reload -dump http://<LOCALIP> 2>&1 | md5sum | cut -d" " -f1 '=<MD5SUM>'
#echo
echo "Incoming attempts:"
#lynx -auth user:password -dump http://10.10.0.1 >> $router 2>&1
check telnet `grep \ 23$ $PWD/router.log | wc -l` '= 0'
check ftp `grep \ 21$ $PWD/router.log | wc -l` '= 0'
check ssh `grep \ 22$ $PWD/router.log | wc -l` '=0'
check smtp `grep \ 25$ $PWD/router.log | wc -l` '=0'
check dns `grep \ 53$ $PWD/router.log | wc -l` '=0'
echo
Some of the lines are commented out for later tweaking. Right now my problem is with the protocols. Not sure what's wrong because it looks like to me there are 3 arguments for the function.
In your last three calls to check, you are missing the required space between the operator and the operand.
check ssh `grep \ 22$ $PWD/router.log | wc -l` '=0'
check smtp `grep \ 25$ $PWD/router.log | wc -l` '=0'
check dns `grep \ 53$ $PWD/router.log | wc -l` '=0'
The final argument to all of these should be '= 0'.
However, this is not a good way to structure your code. If you really need to parameterize the comparison fully (all your calls use = as the operation), pass the operator as a separate argument. Further, written correctly, there is no need to pre-check that $2 is a non-empty string.
check() {
if [ "$2" "$3" "$4" ] ; then
printf '%s%s%s ' "$green" "$1" "$white"
else
printf '%s%s%s ' "$red" "$1" "$white"
printf '%s %s was not %s\n' "$(date)" "$1" "$3" >> "$report"
fi
}
Then your calls to check should look like
check hostname "$(hostname -s)" = localhost
check domain "$(hostname -d)" = domain.com
check ipaddress "$(hostname -I | cut -d" " -f1)" = 10.10.0.6
check gateway "$(netstat -nr | grep ^0.0.0.0 | cut -c17-27)" = 10.10.0.1
etc
Run your code through http://shellcheck.net; there are a lot of things you can correct.
Here is my other problem. I changed it up a bit just to see what's going on.
router=/home/chron/Desktop/router.log
check() {
if [ "$2" "$3" "$4" ]; then
printf "%s%s%s" "$green" "$1" "$white"
else
printf "%s%s%s" "$red" "$1" "$white"
printf "%s %s was not %s\n" "$(date)" "$1" $3" >> report.log
fi
check gateway "$(route | grep 10.10.0.1 | cut -c17-27)" = 10.10.0.1
check telnet "$(grep -c \ 23$ $router)" = 0
check ftp "$(grep -c \ 21$ $router)" = 0
check ssh "$(grep -c \ 22$ $router)" = 0
check smtp "$(grep -c \ 25$ $router)" = 0
check dns "$(grep -c \ 53$ $router)" = 0

how to split a line into array in shell

below script is used for drop a mail while ping dropped in network
subject="Ping failed"
Email="test1#server.abc.com"
awk '{print $1}' < b.txt | while read ip;do
CNT=$(ping -c 1 $ip | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
if [ $CNT -eq 0 ]; then
echo "Host : $ip is down (ping failed) at $(date)"| mail -s "$subject" $Email
fi
done
This script is working fine. Input file has the following content..
192.2.165.1 ttcn
192.3.4.23 dct
192.3.4.24 abc
I want to split lines of this file into 0 and 1 index form like array and mail format should be
Host : $ip ttcn is down (ping failed) at $(date)"
can anyone help me to get this?
To read a line into an array use read -a arr and then access the elements using ${arr[0]}, ${arr[1]} etc.
Also, you don't need to parse the output of ping to check if the host responded. Just use the exit status instead.
Here is the revised version:
while read -r -a arr
do
ip="${arr[0]}"
if ! ping -q -c 1 "$ip" > /dev/null
then
mail -s "$subject" "$email" <<< "Host $ip is down (ping failed) at $(date)"
fi
done < b.txt
Give multiple arguments to read, and each column will be read into the corresponding variable:
while read ip name;do
CNT=$(ping -c 1 $ip | awk -F',' '/received/ { split($2, a, " "); print a[1]}')
if [ $CNT -eq 0 ]; then
echo "Host : $ip $name is down (ping failed) at $(date)"| mail -s "$subject" $Email
fi
done < b.txt
you can use awk
echo "192.2.165.1 ttcn" | awk ' { split($0,a,"");ip=a[1]; print $ip}'

Syntax error: “(” unexpected (expecting “fi”)

filein="users.csv"
IFS=$'\n'
if [ ! -f "$filein" ]
then
echo "Cannot find file $filein"
else
#...
groups=(`cut -d: -f 6 "$filein" | sed 's/ //'`)
fullnames=(`cut -d: -f 1 "$filein"`)
userid=(`cut -d: -f 2 "$filein"`)
usernames=(`cut -d: -f 1 "$filein" | tr [A-Z] [a-z] | awk '{print substr($1,1,1) $2}'`)
#...
for group in ${groups[*]}
do
grep -q "^$group" /etc/group ; let x=$?
if [ $x -eq 1 ]
then
groupadd "$group"
fi
done
#...
x=0
created=0
for user in ${usernames[*]}
do
useradd -n -c ${fullnames[$x]} -g "${groups[$x]}" $user 2> /dev/null
if [ $? -eq 0 ]
then
let created=$created+1
fi
#...
echo "${userid[$x]}" | passwd --stdin "$user" > /dev/null
#...
echo "Welcome! Your account has been created. Your username is $user and temporary
password is \"$password\" without the quotes." | mail -s "New Account for $user" -b root $user
x=$x+1
echo -n "..."
sleep .25
done
sleep .25
echo " "
echo "Complete. $created accounts have been created."
fi
I'm guessing the problem is that you're trying to capture command output in arrays without actually using command substitution. You want something like this:
groups=( $( cut... ) )
Note the extra set of parentheses with $ in front of the inner set.

Resources