📑

WSL2 UbuntuでhostのWindowsからdns serverのアドレスを取得して、設定する

2024/07/05に公開

/etc/resolve.conf
に windows側で使用されているdns server のアドレスを設定するためのスクリプト。

#!/bin/bash

# Check if running with sudo
if [[ $EUID -ne 0 ]]; then
  echo "This script must be run with sudo privileges." 1>&2
  exit 1
fi

# Path to Windows PowerShell executable
powershell_path="/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe"

# Get DNS server addresses from Windows
dns_servers=$($powershell_path "(Get-DnsClientServerAddress -AddressFamily IPv4).ServerAddresses -join \"\`n\"")

# Backup /etc/resolv.conf
cp /etc/resolv.conf /etc/resolv.conf.bk

tee /etc/resolv.conf <<EOL > /dev/null
# This file is managed by a script. Do not edit manually.
$(echo "$dns_servers" | sed 's/^/nameserver /; s/\n$//')
EOL

echo "Updated /etc/resolv.conf with DNS servers:"
echo "$dns_servers"

Discussion