WSL1 与VPN
目录
注意
本文最后更新于 2024-01-20,文中内容可能已过时。
原文链接:https://ovea-y.cn/windows_wsl1_and_vpn/
WSL1 与VPN
- Get-NetAdapter -InterfaceDescription 获取所有网络适配器信息
其中TAP-Windows Adapter V9 和Cisco AnyConnect Secure Mobility Cli都是VPN
- Get-DnsClientServerAddress 获取DNS服务器地址
背景
由于使用了VPN后,VPN的DNS信息不会自动同步到WSL 1中,因此需要一种方法来快捷配置WSL 1的DNS服务器信息。
配置
vpn配置
首先需要找到目前使用的VPN适配器是哪个,然后配置进WSL 1的配置文件中。
#run to fix connection / nameserver issues when connected to VPN
vpn () {
#Write dns servers from VPN interface to /etc/resolv.conf
# powershell.exe -Command 'Get-NetAdapter -InterfaceDescription "Cisco AnyConnect*" | Get-DnsClientServerAddress | Select -ExpandProperty ServerAddresses' | awk 'BEGIN { print "# Generated by vpn fix func on", strftime("%c"); print } { print "nameserver", $1 }' | tr -d '\r' | sudo tee /etc/resolv.conf
powershell.exe -Command 'Get-NetAdapter -InterfaceDescription "TAP-Windows Adapter*" | Get-DnsClientServerAddress | Select -ExpandProperty ServerAddresses' | awk 'BEGIN { print "# Generated by vpn fix func on", strftime("%c"); print } { print "nameserver", $1 }' | tr -d '\r' | sudo tee /etc/resolv.conf
# ## ^VPN^PROVIDER^INTERFACE^NAME^ ##
#Script to set interface metric correctly, since admin is required, some extra code to elevate rights.
powershell.exe -File 'C:\\Users\\miove\\dev\\Scripts\\vpn.ps1'
# ^YOUR SCRIPT LOCATION IN WINDOWS FORMAT^
#
#THE SCRIPT SHOULD CONTAIN:
#
#if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
# Start-Process PowerShell -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"";
# exit;
#}
#Get-NetAdapter | Where-Object {$_.InterfaceDescription -Match "Cisco AnyConnect"} | Set-NetIPInterface -InterfaceMetric 6000
# ## ^VPN^PROVIDER^INTERFACE^NAME^ ##
#
}
回到正常状态
notvpn () {
echo "# generated by ~/.bashrc notvpn () "
echo "nameserver 8.8.8.8" | tr -d '\\r' | sudo tee /etc/resolv.conf
echo "nameserver 8.8.4.4" | tr -d '\\r' | sudo tee /etc/resolv.conf
}
这些方法放在bash的配置文件中就能在命令行中直接执行对应的方法来生效了。