Linux Overrides /Etc/Hosts on Windows-Linux-Subsystem

Linux Overrides /Etc/Hosts on Windows-Linux-Subsystem

I had problems with hostnames resolving in windows Linux-subsystem so I removed /etc/hosts and wrote new version of it. That solution solved my problem, but after every reboot system started overriding /etc/hosts by a some default version, so I need setup hosts again and again. Is it possible to setup linux subsystem so it copies original windows hosts file or at least doesn't delete already written file ?

5 Answers

sudo vim /etc/wsl.conf

Add the following two lines:

[network]
generateHosts = False

Reference:

1

I am using Ubuntu 16.04.5 LTS as a Linux subsystem under Windows. My /etc/hosts file under Ubuntu says

#This file is automatically generated by WSL based on the Windows hosts file:
#%WINDIR%\System32\drivers\etc\hosts. Modifications to this file will be overwritten.

So I simply changed the #%WINDIR%\System32\drivers\etc\hosts instead.

1

I did not have the line saying: To prevent automatic generation of this file, remove this line.in my /etc/hosts.

What I ended up doing was creating an addHosts.sh script with the following content:

MYHOSTS="ip1\thostname1\nip2\thostname2"
grep hostname1 /etc/hosts >> /dev/null || echo $MYHOSTS | sudo tee -a /etc/hosts >> /dev/null

The grep prevents adding the entries multiple times if you open separate instances of your linux distro.

Afterwards you have to add sudo addHosts.sh to your bashrc and (optionally) create an exception for sudo password prompt for this script in /etc/sudoers:

user ALL = (root) NOPASSWD: /path/to/addHosts.sh

Your issue is adressed here:

To prevent WSL from automatically generating the /etc/hosts file on every bash startup, you need to remove the following comment line in /etc/hosts:

# This file was automatically generated by WSL. To prevent automatic generation of this file, remove this line.

I had to do chattr +i on the file because the file kept getting overwritten even after I followed the instructions to add those two lines to /etc/wsl.conf.

NOTE - remember that you ll need chattr -i to be able to edit the file from anywhere again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi
Author

Maya Lin-Takahashi

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.