Files
shell-scripts/基础脚本/获取本机的内网IP.sh
2024-11-27 10:33:20 +08:00

55 lines
1.7 KiB
Bash
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
InnerIPv4CIDR=""
InnerIPv6CIDR=""
InnerIPv4=""
InnerIPv6=""
# 获取服务器的公网IP地址
get_Internal_IP_CIDR() {
local interface_prefix=("[[:space:]]eth[0-9]{1,2}" "[[:space:]]ens[0-9]{1,3}" "[[:space:]]eno[0-9]{1,3}" "[[:space:]]enp[0-9]{1,2}")
local real_interface="eth90"
for interface in "${interface_prefix[@]}"; do
echo $(ip link show) | grep -oE ${interface} | head -1
if [[ $? -eq 0 ]]; then
real_interface=$(echo $(ip link show) | grep -oE ${interface} | head -1 | cut -d" " -f2)
echo "当前主机的真实内网网卡为 => [$real_interface]"
break
fi
done
# 提取IPv4地址CIDR格式
local ipv4_regex="inet[[:space:]](25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\/[0-9]{1,2}"
# 提取IPv6地址CIDR格式
loca ipv6_regex="inet6[[:space:]]([0-9a-fA-F]{0,4}(:[0-9a-fA-F]{0,4}){1,7})\/[0-9]{1,3}"
# 查找IPv4地址
local inner_ipv4=$(echo $(ip addr show $real_interface) | grep -oE $ipv4_regex | cut -d" " -f2)
InnerIPv4CIDR=$inner_ipv4
echo "Interface: $real_interface, IPv4 Address: $inner_ipv4"
# 查找IPv6地址
local inner_ipv6=$(echo $(ip addr show $real_interface) | grep -oE $ipv6_regex | cut -d" " -f2)
InnerIPv6CIDR=$inner_ipv6
echo "Interface: $real_interface, IPv4 Address: $inner_ipv6"
}
get_Internal_IP_() {
get_Internal_IP_CIDR
InnerIPv4=$(echo $InnerIPv4CIDR | cut -d "/" -f1)
InnerIPv6=$(echo $InnerIPv6CIDR | cut -d "/" -f1)
echo "服务器的内网IPv4地址为 $InnerIPv4"
echo "服务器的内网IPv6地址为 $InnerIPv6"
}
get_Internal_IP_CIDR