Skip to content

Instantly share code, notes, and snippets.

@Adriem
Last active November 19, 2018 09:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Adriem/336d0177ebaeb1565b95a02596b3c94c to your computer and use it in GitHub Desktop.
Save Adriem/336d0177ebaeb1565b95a02596b3c94c to your computer and use it in GitHub Desktop.
Simple script for updating the /etc/hosts file
#!/usr/bin/env node
/** @author Adrian Moreno (https://github.com/adriem) */
const https = require('https')
const fs = require('fs')
const urls = process.argv.slice(2).filter(arg => arg !== '-v' && arg !== '--verbose')
const verbose = process.argv.includes('-v') || process.argv.includes('--verbose')
const defaultUrls = [
// PUT YOUR DEFAULT URLS HERE
]
async function fetchIp(url) {
const dnsData = await new Promise((resolve, reject) => {
let rData = ''
https
.get(`https://dns.google.com/resolve?name=${url}`, (response) => {
response.on('data', (chunk) => rData += chunk)
response.on('end', () => resolve(JSON.parse(rData)['Answer']))
})
.on('error', reject)
})
return dnsData.find((it) => it.type == 1).data
}
async function updateHostsFile(urls) {
let hostsFileContent = fs.readFileSync('/etc/hosts', 'utf8')
await Promise.all(urls.map(async url => {
const entryRegex = new RegExp(`[\\.\\d]*[ \\t]+${url}`, 'ig')
const newHostEntry = `${await fetchIp(url)}\t${url}`
const isExistingEntry = entryRegex.test(hostsFileContent)
hostsFileContent = isExistingEntry
? hostsFileContent.replace(entryRegex, newHostEntry)
: `${hostsFileContent}${newHostEntry}\n`
if (verbose) console.log(`ENTRY UPDATED: ${newHostEntry}`)
}))
fs.writeFileSync('/etc/hosts', hostsFileContent, 'utf8')
}
updateHostsFile(urls.length > 0 ? urls : defaultUrls)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment