#!/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