Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

shell - Efficient way to get ip addresses based on a list of hostnames

I had to gather a list of IP addresses from a list of hostnames, this is what I came up with:

#!/bin/bash                                                                                                
Hosts='host1 host2 host3 host4 host5 host6 host7' 

for h in $Hosts                                                                                            
do                                                                                                         
    echo "$h : " $(ping -c 1 $h | egrep -o -m 1 '([0-9]+.[^(
]*)')    done 

Is there a more efficient way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you mean the latency gets you down, you can do them all in parallel with GNU Parallel:

parallel -a hosts 'echo -n {}; ping -c1 {} |egrep -o -m 1 "([0-9]+.[^(
]*)"'

The -a hosts assumes you have the hostnames in a file called hosts.

hosts:

virgin
router

Output:

virgin(192.168.100.1)
router(192.168.0.1)

Or, if you don't want a file of hostnames, you can use your loop:

for h in virgin router; do 
   echo $h; 
done | parallel 'echo -n {}; ping -c1 {} |egrep -o -m 1 "([0-9]+.[^(
]*)"'

Alternatively, have a look in the arp cache...

arp router
router.asus.com (192.168.0.1) at 8:60:6e:ba:17:c8 on en0 ifscope [ethernet]

arp virgin
virgin (192.168.100.1) -- no entry

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...