Skip to content

Instantly share code, notes, and snippets.

@Kcharle
Last active November 30, 2021 14:38
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 Kcharle/1c8c9cd18e83deb3a59a20022c00bc37 to your computer and use it in GitHub Desktop.
Save Kcharle/1c8c9cd18e83deb3a59a20022c00bc37 to your computer and use it in GitHub Desktop.
(Python) WSL - Update Windows Hosts File IP's Automatically

WSL 2 - Automatically update all entries in /mnt/c/Windows/System32/drivers/etc/hosts

Requirements - Before running this script, you will need to add the following as the first line of your hosts file #previp:place_current_ip_here

Make sure to replace place_current_ip_here with the current value returned in wsl from hostname -I, this is what the script looks for the know what to replace.

To run - Open a Powershell instance with administrator privileges and execute the python script python \path\to\file\wsl-hosts-rename.py

import subprocess as sp
import os
file1 = open("C:\\Windows\\System32\\drivers\\etc\\hosts","r+");
fout = open("C:\\Windows\\System32\\drivers\\etc\\hosts2", "wt")
newIP = sp.getoutput('wsl hostname -I')
oldIP = ""
index = 0
for line in file1:
if index == 0:
oldIP = line.split("#previp:",1)[1].strip()
fout.write(line.replace(oldIP, newIP))
index = index + 1
print ("Replaced " + oldIP + " with " + newIP)
file1.close()
fout.close()
if os.path.exists("C:\\Windows\\System32\\drivers\\etc\\hosts"):
os.remove("C:\\Windows\\System32\\drivers\\etc\\hosts")
else:
print("The file does not exist")
if os.path.exists("C:\\Windows\\System32\\drivers\\etc\\hosts2"):
os.rename("C:\\Windows\\System32\\drivers\\etc\\hosts2", "C:\\Windows\\System32\\drivers\\etc\\hosts")
else:
print("The file does not exist")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment