跳到主內容

【Shell】【Tip】列出環境變數網址解析dns

image-1747466952908.png

#!/bin/bash

export A_HOST="https://www.google.com/a/b"
export B_HOST="https://tw.yahoo.com/a?a=a&b=b"
export C_HOST="https://www.microsoft.com/zh-tw/#bb"

echo "列出所有環境變數並解析疑似網址的 IP:"
echo "========================================="

# 顯示目前 DNS server
# 嘗試從 systemd-resolved 的配置中找出真實 DNS
if command -v resolvectl >/dev/null 2>&1; then
  dns_servers=$(resolvectl status | grep 'DNS Servers' | head -n 1 | awk -F': ' '{print $2}')
#elif [ -f /run/systemd/resolve/resolv.conf ]; then
#  dns_servers=$(grep -E '^nameserver' /run/systemd/resolve/resolv.conf | awk '{print $2}')
else
  dns_servers=$(grep -E '^nameserver' /etc/resolv.conf | awk '{print $2}')
fi

echo "目前使用的 DNS server:$dns_servers"
echo "-----------------------------------------"

# 暫存解析過的域名,避免重複查詢
declare -A resolved

while IFS='=' read -r name value; do
  if [[ "$value" =~ ^https?://([^:/]+) ]]; then
    host="${BASH_REMATCH[1]}"
  elif [[ "$value" =~ ^([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})$ ]]; then
    host="${BASH_REMATCH[1]}"
  else
    continue
  fi

  if [[ -n "$host" && -z "${resolved[$host]}" ]]; then
    ip=$(dig +short "$host" | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' | head -n 1)
    resolved["$host"]="$ip"
    echo "$name=$value"
    if [[ -z "$ip" ]]; then
      echo " ↳ $host → [無法解析]"
    else
      echo " ↳ $host → $ip"
    fi
    echo "-----------------------------------------"
  fi
done < <(env)

echo ""
echo "系統 /etc/hosts 內容(不含註解與空行):"
echo "========================================="
grep -vE '^\s*#|^\s*$' /etc/hosts