1

recently we got Jump Host to interact with all our devices. It's red had 6.x and we have no root access. We can script on Autoexpect and bash only - no modules possible.

Source: I have 5000 devices (1 per line, 3 arguments each - Location HostName IP - and they are tab separated).

Task: Search for all devices per location (ARGV1) (say out 5000, 40 would be for one location), redirect the output to a temp file (no output, echo off) and run a command for each device in the temp directory. Output should be for HostName ARGV2 not IP.

Say ping each device in tmp and return success for each host, or log into each device, run command, output result for the host and move to the next in the tmp file.

Input file structure example:

AA Torp1 1.1.1.1 
AA Torp2 2.2.2.2
BB Torp97 9.9.9.9

Say you want to ping each device from locaton AA. How do I script the cat hosts.txt | grep AA to tmp and then ping each IP e.g. 1.1.1.1 and 2.2.2.2 and output is :

Torp1 OK if ping succeed Torp2 NOK if ping not ok

Its the basic example ....or say for each IP grepped based on location, ssh , run command print output and then remove the tmp file.

0

1 Answer 1

1

The simple way to do this is to use a while read loop. The general format is:

while read var1 var2 ... varN; do something; done < inputFile

By default, each input line is split on whitespace, so this is already essentially what you need:

while read location hostname ip; do
    printf "Ping of $hostname ($ip): "
    ping -c1 "$ip" &>/dev/null && echo "OK" || echo "FAILED"
done < ips.txt

Or, to limit to a specific location:

grep location ips.txt | while read location hostname ip; do
    printf "Ping of $hostname ($ip): "
    ping -c1 "$ip" &>/dev/null && echo "OK" || echo "FAILED"
done

If we test this with this file:

location1 example.com 93.184.216.34
location2 google.com 8.8.8.8
location1 bad.com 123.456.7.8

We get:

$ grep -w "^$location" ips.txt | 
    while read location hostname ip; do     
        printf "Ping of $hostname ($ip): ";     
        ping -c1 "$ip" &>/dev/null && echo "OK" || echo "FAILED"; 
    done 
Ping of example.com (93.184.216.34): OK
Ping of bad.com (123.456.7.8): FAILED
2
  • Where are you passing the argument exactly if this is say location.sh file? so ...../location.sh "location"
    – kjydr
    Jun 7, 2019 at 16:10
  • @kjydr no, only those lines in the output of grep location ips.txt. But if the location is always the first word on the line, use grep -w '^location' instead, so that location1 won't also find location11 or a domain called location1.com.
    – terdon
    Jun 7, 2019 at 16:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .