簡體   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