0

below script is used for drop a mail while ping dropped in network

subject="Ping failed"
Email="[email protected]"
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?

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Great! its solved me what i was looking. another query here is there any way to create excelfile for capturing the output for the same. can we do this in shell?
1

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

1 Comment

thanks it works for me. if I add 3 argument then what would be the split function? like 192.2.165.1 ttcn abc and mail format accordingly.
0

you can use awk

 echo "192.2.165.1 ttcn" | awk ' { split($0,a,"");ip=a[1]; print $ip}' 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.