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

33 lines
861 B
Bash
Raw 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
# 判断命令是否存在
command_exists() {
command -v "$@" >/dev/null 2>&1
}
# 获取服务器的公网IP地址
get_server_ip() {
local server_ip=""
local Network_Manage_Tool=""
if command_exists ip; then
Network_Manage_Tool="$(ip addr)"
elif command_exists ifconfig; then
Network_Manage_Tool="$(ifconfig)"
fi
server_ip=$(echo "$Network_Manage_Tool" | \
grep -oE "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" | \
grep -vE "^192\.168|^172\.1[6-9]\.|^172\.2[0-9]\.|^172\.3[0-2]\.|^10\.|^127\.|^255\.|^0\." | \
head -n 1)
# 自动获取失败时,通过网站提供的 API 获取外网地址
if [ -z "$server_ip" ]; then
server_ip="$(wget -qO- --no-check-certificate https://ipv4.icanhazip.com)"
server_ip=$(curl -s https://myip.ipip.net | awk '{print$2}' | cut -d"" -f2)
fi
echo "$server_ip"
}
get_server_ip