[英]How to get hostname from IP address from file similar to /etc/hosts
I have a file which maps IP Address to hostname.我有一个将 IP 地址映射到主机名的文件。 Its format is similar to hosts file and contains a list of ipaddress to hostname mapping.它的格式类似于主机文件,并包含一个 ipaddress 到主机名映射的列表。
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.我想使用 bash 脚本从给定的 ipaddress 获取主机名。
How can i do so?我怎么能这样做?
You can try that :你可以试试:
sh script.sh listofip 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
In Bash 4, I would use an associative array;在 Bash 4 中,我会使用关联数组; see http://mywiki.wooledge.org/BashFAQ/006#Associative_Arrays见http://mywiki.wooledge.org/BashFAQ/006#Associative_Arrays
For older versions of Bash, maybe use a simple wrapper such as对于旧版本的 Bash,也许使用一个简单的包装器,例如
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
}
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}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.