1830939 Members
2844 Online
110017 Solutions
New Discussion

Server names and its IPs

 
SOLVED
Go to solution
Shivkumar
Super Advisor

Server names and its IPs

Hello,

I have some server names and there are entries related to it in /etc/hosts file.
The /etc/hosts file contains more IPs also.

I need a shell script which can output server names and
its related IPs from /etc/hosts file.

Can someone help me ?

Thanks,
Shiv
2 REPLIES 2
Bill Hassell
Honored Contributor
Solution

Re: Server names and its IPs

I think what oyu meant was that you have a file with just server names and you want to search through /etc/hosts for a match. Although the simplest is a simple grep, you may have hostnames that are part of other hostnames (or no match at all). And you must skip comments in /etc/hosts since they are ignored by networking software. So here is an example:

#!/usr/bin/sh
# Usage: lookup hostname-file
# Returns IP address for a hostname match
set -u
export PATH=/usr/bin
export MYNAME=${0##*/}
function Usage
{
[ $# -gt 0 ] && print "\n$@"
print "Usage: $MYNAME "
exit 1
}
# Main program
[ $# -ne 1 ] && Usage "Requires one filename"
MYFILE=$1
[ -r $MYFILE ] || Usage "$MYFILE not found"
cat $MYFILE | while read HOST JUNK
do
grep -v "^\#" /etc/hosts | while read IP HOSTNAMES
do
if [ $(print "$HOSTNAMES" | grep -wc $HOST) -gt 0 ]
then
print "$HOST = $IP"
fi
done
done

---------------------------------

You can add some other details like reporting on hostnames not found. This script will report all occurrences of the hostname so if /etc/hosts hasa multiple entries, you'll see those too.


Bill Hassell, sysadmin
James R. Ferguson
Acclaimed Contributor

Re: Server names and its IPs

Hi Shiv:

As Bill noted, the simplest solution may be to use 'grep's options. Assuming, as he said, that you have a file of server names and you want to match those in '/etc/hosts' you can do:

# grep -f /tmp/myhosts /etc/hosts|grep -v "^#"

...to find tokens in 'myhosts' that exist in '/etc/hosts' and skip any comment lines.

# grep -v -f /tmp/hosts /etc/hosts|grep -v "^#"

...to find tokens in 'myhosts' that do _NOT_ exist in '/etc/hosts'.

Regards!

...JRF...