abcd_e
abcd_e

Reputation: 11

bash script - 2 variables in loop

I have a file ip_details.txt with following;

Peer "ATBBB010.domain.com:1111;transport=tcp" ConnectAddress="10.184.88.29,10.184.88.30" LocalPort="0"
Peer "ATBBB020.domain.com:1111;transport=tcp" ConnectAddress="10.184.88.61,10.184.88.62" LocalPort="0"
Peer "CHBBB010.domain.com:1111;transport=tcp" ConnectAddress="10.161.144.5,10.161.144.6" LocalPort="0"
Peer "CHBBB020.domain.com:1111;transport=tcp" ConnectAddress="10.161.144.21,10.161.144.22" LocalPort="0"
Peer "DABBB010.domain.com:1111;transport=tcp" ConnectAddress="10.160.130.5,10.160.130.6" LocalPort="0"
Peer "DABBB020.domain.com:1111;transport=tcp" ConnectAddress="10.160.130.21,10.160.130.22" LocalPort="0"
Peer "ATCCC010.domain.com:1111;transport=tcp" ConnectAddress="10.199.88.29,10.199.88.30" LocalPort="0"
Peer "ATCCC020.domain.com:1111;transport=tcp" ConnectAddress="10.199.88.61,10.199.88.62" LocalPort="0"
Peer "CHCCC010.domain.com:1111;transport=tcp" ConnectAddress="10.161.155.5,10.161.155.6" LocalPort="0"
Peer "CHCCC020.domain.com:1111;transport=tcp" ConnectAddress="10.161.155.21,10.161.155.22" LocalPort="0"
Peer "DACCC010.domain.com:1111;transport=tcp" ConnectAddress="10.199.130.5,10.199.130.6" LocalPort="0"
Peer "DACCC020.domain.com:1111;transport=tcp" ConnectAddress="10.199.130.21,10.199.130.22" LocalPort="0"

I currently use these 2 scripts/commands to ping the IP Addresses of the specific type nodes.

To Ping the BBB nodes first IP (IP before the comma delimiter);

for i in `cat ip_details.txt | grep BBB | awk '{print $3}' | cut -d= -f2 | cut -d, -f1 | tr -d '[="=]'`; do ping -I eth0 -c 3 $i >> /dev/null ; [ $? != 0 ] && echo $i || echo "Ping to $i Good"; done

To Ping the BBB nodes 2nd IP (IP after the comma delimiter);

for i in `cat ip_details.txt | grep BBB | awk '{print $3}' | cut -d= -f2 | cut -d, -f2 | tr -d '[="=]'`; do ping -I eth0 -c 3 $i >> /dev/null ; [ $? != 0 ] && echo $i || echo "Ping to $i Good"; done

I get the as the following;

Ping to 10.184.88.29 Good
Ping to 10.184.88.61 Good
.
.

Similarly I grep CCC for CCC Nodes.

I need a script to ping these IP Addresses per nodes types or both types together and get output like this;

Ping from <hostname> to ATBBB010 IP1 <ip address> is Good
....
....
....

Ping from <hostname> to ATBBB010 IP2 <ip address> is Good 
....
....
....

If the ping fails;

Ping from <hostname> to ATBBB010 IP1 <ip address> failed
.....
.....

Ping from <hostname> to ATBBB010 IP2 <ip address> failed
.....
.....

Upvotes: 1

Views: 98

Answers (1)

mklement0
mklement0

Reputation: 437100

Try the following:

#!/usr/bin/env bash

msgPrefix="Ping from $HOSTNAME to"
prevNode=
while read node ip; do
  [[ "$node" == "$prevNode" ]] || i=1
  ping -I eth0 -c 3 "$ip" >/dev/null && status='is good' || status='failed'
  echo "$msgPrefix $node IP$i $ip $status"
  ((++i)); prevNode=$node
done < <(awk -F'"|\\.domain\\.com|,' '{ print $2, $5 }' ip_details.txt)

Upvotes: 1

Related Questions