How to get hostname from IP address from file similar to /etc/hosts

*爱你&永不变心* 提交于 2019-12-20 06:19:47

问题


I have a file which maps IP Address to hostname. Its format is similar to hosts file and contains a list of ipaddress to hostname mapping.

eg.

10.200.99.1    master1
10.200.99.2    master2
10.200.99.3    master3
10.200.99.4    slave1
10.200.99.5    slave2
10.200.99.6    slave3
...
...
...

I would like to obtain hostname from a given ipaddress using bash script.

How can i do so?


回答1:


You can try that :

sh script.sh listofip

#!/bin/bash

        echo  "IP ?"
        echo -n "(Value and press Enter) :"
        read ip


while read line
do
#VARIABLES
file1=$line
mip=$(echo $file1 | awk '{print $1}')
name=$(echo $file1 | awk '{print $2}')


    if [ "$mip" = "$ip" ]
        then
        echo "Machine name is " $name
    fi

done < $1

results :

IP ?
(Value and press Enter) :10.200.99.2
Machine name is  master2



回答2:


In Bash 4, I would use an associative array; see http://mywiki.wooledge.org/BashFAQ/006#Associative_Arrays

For older versions of Bash, maybe use a simple wrapper such as

lookup () {
    echo "$1" |
    awk 'NR==FNR { a[$1] = $2; next }
        $1 in a { print a[$1]; exit 0 }
        END { exit 1 }' input.txt -
}

This is slightly inelegant in that it requires the file to exist in the current directory. You can embed the mapping file in the script itself, though that requires some modest refactoring (the here document will tie up standard input so you cannot pipe your input to the script which reads it).

lookup () {
    awk -v q="$1" '$1 == q { print $2; exit 0 }
            END { exit 1 }' <<'________HERE'
        10.200.99.1    master1
        10.200.99.2    master2
        10.200.99.3    master3
        10.200.99.4    slave1
        10.200.99.5    slave2
        10.200.99.6    slave3
________HERE
}



回答3:


I got a much simpler solution

#!/bin/bash

### GET IP ADDRESS ###
    echo  "IP Address ?"
    echo -n "(Value and press Enter) :"
    read ip_address

### Find Hostname matching to IPADDRESS ###
    grep  $ip_address /etc/hosts | awk '{print $2}'


来源:https://stackoverflow.com/questions/32864101/how-to-get-hostname-from-ip-address-from-file-similar-to-etc-hosts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!