Skip to content

Instantly share code, notes, and snippets.

@nfekete
Created August 8, 2018 03:05
Show Gist options
  • Select an option

  • Save nfekete/7a277bf9e25e89e1c8bfb8b64dcc08ed to your computer and use it in GitHub Desktop.

Select an option

Save nfekete/7a277bf9e25e89e1c8bfb8b64dcc08ed to your computer and use it in GitHub Desktop.
Fix resolv.conf in Windows Subsystem for Linux, when WSL doesn't correctly generate it.
#!/bin/bash
TMP=`mktemp`
trap ctrlC INT
removeTempFiles() {
rm -f $TMP
}
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 `/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe -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
(set -x; sudo cp -i $TMP /etc/resolv.conf)
removeTempFiles
@nfekete

nfekete commented Oct 2, 2020

Copy link
Copy Markdown
Author

@jhanssenfavaro you're welcome

@Davidffry

Copy link
Copy Markdown

Really great!

@Yumash

Yumash commented Nov 6, 2020

Copy link
Copy Markdown

..also, if you want add some own lines to it - please - remember do

wsl --shutdown

in Windows cmd or powershell

Please note that at least one WSL session must be open to save your own resolv.conf for future sessions.

@mrlinux11

Copy link
Copy Markdown

Unfortunately this did not resolve my issue (no pun intended)

@raulvictorrosa

Copy link
Copy Markdown

For me it did not resolve too.

@MatMercer

Copy link
Copy Markdown

Thanks for sharing your script!

I created a new version for it here: https://gist.github.com/MatMercer/f7e25b9c8ce7ca40dd3b220346136d23

@raulvictorrosa you can try it.

@TheLandolorien

TheLandolorien commented Nov 9, 2021

Copy link
Copy Markdown

Perfect! I still needed to run the following (Source: anyconnect WSL 2 - Windows Substem for Linux) to get enable the interface on the VPN

Get-NetAdapter | Where-Object {$_.InterfaceDescription -Match "Cisco AnyConnect"} | Set-NetIPInterface -InterfaceMetric 4000
Get-NetIPInterface -InterfaceAlias "vEthernet (WSL)" | Set-NetIPInterface -InterfaceMetric 1

But that doesn't provide the DNS resolution. The resolv.conf update was the missing piece.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment