Last active
December 20, 2023 23:52
-
-
Save jimfrenette/21c7f19bc12c94c60628bebbf943a974 to your computer and use it in GitHub Desktop.
For WSL2 Linux: get IP from `/etc/resolv.conf` and update `/etc/hosts`. A use case for this is when you want to target localhost on Windows from Linux on WSL2. https://jimfrenette.com/2020/07/wsl2-windows-terminal/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# the directory that contains this script | |
base=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P ) | |
function removehost() { | |
if [ -n "$(grep $HOSTNAME /etc/hosts)" ] | |
then | |
echo "$HOSTNAME Found in your /etc/hosts, Removing now..."; | |
sudo sed -i".bak" "/$HOSTNAME/d" /etc/hosts | |
else | |
echo "$HOSTNAME was not found in your /etc/hosts"; | |
fi | |
addhost | |
} | |
#add new ip host pair to `/etc/hosts` | |
function addhost() { | |
if [ -n "$(grep $HOSTNAME /etc/hosts)" ] | |
then | |
echo "$HOSTNAME already exists:"; | |
echo $(grep $HOSTNAME /etc/hosts); | |
else | |
echo "Adding $HOSTNAME to your /etc/hosts"; | |
printf "%s\t%s\n" "$IP" "$HOSTNAME" | sudo tee -a /etc/hosts > /dev/null; | |
if [ -n "$(grep $HOSTNAME /etc/hosts)" ] | |
then | |
echo "$HOSTNAME was added succesfully:"; | |
echo $(grep $HOSTNAME /etc/hosts); | |
else | |
echo "Failed to Add $HOSTNAME, Try again!"; | |
fi | |
fi | |
} | |
# windows localhost hostname to add/update in `/etc/hosts` | |
if [ "$1" != "" ]; then | |
HOSTNAME=$1 | |
else | |
echo "Enter hostname to add or update, e.g., win.localhost" | |
read -p 'HOSTNAME: ' HOSTNAME | |
fi | |
# get IP from nameserver in `/etc/resolv.conf` | |
# from `https://rimuhosting.com/knowledgebase/linux/misc/checking-your-resolv.conf-file` | |
ns=$(cat /etc/resolv.conf | grep -v '^#' | grep nameserver | awk '{print $2}') | |
for i in $ns; do ptr=$(host $i | sed 's/Name: //' | sed 's/ .*//g' | head -n 1) | |
echo $i | |
IP=$i | |
removehost | |
# if dig @$i -t ns rimuhosting.com |grep -qai 'rimuhosting'; then | |
# echo $i $ptr OK; | |
# else | |
# echo $i $ptr failed; | |
# fi; | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @dhulke