Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Replaces ip address in hosts file with the WSL2 container's ip
import * as shelljs from 'shelljs';
import * as fs from 'fs';
let modifyHosts = ['somehost.tld', 'testing.localdev'];
(shelljs.exec(`ip addr | grep "scope global eth0"`, {async: true}).stdout as any).on('data', (data) => {
if (data.includes('scope global eth0')) {
let ip = data.replace('inet ', '').split('/')[0].trim();
let hosts = fs.readFileSync("/mnt/c/Windows/System32/drivers/etc/hosts", {encoding: 'utf-8'})
.split('\n');
fs.writeFileSync("/mnt/c/Windows/System32/drivers/etc/hosts", hosts.map(line => {
if (!line.includes('#') && line.includes('\t')) {
let parsed = line.split('\t');
let parsedHost = parsed[1].replace('\r', '');
if (modifyHosts.find(h => h === parsedHost)) {
return ip + '\t' + parsedHost + '\r';
}
}
return line;
}).join('\n'), {encoding: 'utf-8'});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment