繁体   English   中英

如何使用bash找出您的IP地址

[英]How to find out your IP addresses using bash

我有一台具有多个IP地址的服务器。 我想用bash计算出它们的确切值。 我正在寻找类似的东西:

a=returnIpAddressStartingWith 10.60.12
b=returnIpAddressStartingWith 10.60.13

以便返回以下内容:

> echo $a
10.60.12.23

在Linux上有这样做的合理方法吗?

您可以使用以下函数进行搜索:

findip() {
   ip -4 addr | awk -v ip="$1" -F '[/[:blank:]]+' '$2 == "inet" && index($3, ip){print $3}'
}

并通过以下方式找到IP:

a=$(findip '10.60.12')

使用grep / awk / cut将其从“ ip addr show”列表中解析出来,然后(可选)(如果需要以数组形式访问它)将列表复制到Bash数组中:

# Create a string that is the list of all variables
IPSTR=`ip addr show | fgrep 'inet ' | fgrep -v '127.0.0.1' | awk '{ print $2 }' | cut -d '/' -f 1`
I=0
for IP in $IPSTR ; do
    IPARY[$I]=$IP
    I=$(($I+1))
done
echo "First IP in array is ${IPARY[0]}"
echo "Number of IP addresses in array is ${#IPARY[*]}"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM