Skip to content

Instantly share code, notes, and snippets.

@ThiagoBarradas
Forked from MatMercer/wsl-vpn-fix.sh
Last active February 4, 2022 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThiagoBarradas/c5c28931ce81b053873820bcb0e08ed4 to your computer and use it in GitHub Desktop.
Save ThiagoBarradas/c5c28931ce81b053873820bcb0e08ed4 to your computer and use it in GitHub Desktop.
Fix WSL 2 DNS resolution when connected to Cisco AnyConnect VPN
#!/bin/bash
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
exit 1
fi
TMP_DIR=`mktemp -d`
TMP_SCRIPT="$TMP_DIR/network-metrics.ps1"
TMP_RESOLV="$TMP_DIR/resolv.conf"
POWERSHELL="powershell.exe"
touch "$TMP_SCRIPT"
# this starts the script as admin in powershell
pcmd="Start-Process -FilePath $POWERSHELL -verb runas -ArgumentList $POWERSHELL,-noprofile,-executionpolicy,bypass,-file,$(wslpath -aw $TMP_SCRIPT)"
# generate the fix script
echo 'Get-NetIPInterface -InterfaceAlias "vEthernet (WSL)" | Set-NetIPInterface -InterfaceMetric 1
Get-NetAdapter | Where-Object {$_.InterfaceDescription -Match "Cisco AnyConnect"} | Set-NetIPInterface -InterfaceMetric 6000' > $TMP_SCRIPT
# required to allow windows do read the folder contents
chmod 777 $TMP_DIR
trap ctrlC INT
removeTempFiles() {
# powershell continues in the background, trying to use a file that was deleted. TODO: fix the racing condition
# rm -rf $TMP_DIR
true
}
ctrlC() {
echo
echo "Trapped Ctrl-C, removing temporary files"
removeTempFiles
stty sane
}
echo "Current resolv.conf"
echo "-------------------"
cat /etc/resolv.conf
echo
echo "Creating new resolv.conf"
echo "------------------------"
{
head -1 /etc/resolv.conf | grep '^#.*generated'
for i in `$POWERSHELL -Command "Get-DnsClientServerAddress -AddressFamily ipv4 | Select-Object -ExpandProperty ServerAddresses"`; do
echo nameserver $i
done
tail -n+2 /etc/resolv.conf | grep -v '^nameserver'
} | tr -d '\r' | tee $TMP_RESOLV
(set -x; cp -i $TMP_RESOLV /etc/resolv.conf; set +x)
echo
echo "Fixing network metrics for cisco anyconnect"
echo "-------------------------------------------"
cat $TMP_SCRIPT
# run the network metrics fix script
$POWERSHELL -command "$pcmd"
removeTempFiles
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment