Skip to content

Instantly share code, notes, and snippets.

@h0tw1r3
Created Apr 19, 2020
Embed
What would you like to do?
Work-around issues with WSL DNS resolver
#!/bin/bash
# Based on https://gist.github.com/matthiassb/9c8162d2564777a70e3ae3cbee7d2e95
PATH=/sbin:/bin
WINSYS32=/mnt/c/Windows/System32
PS=$WINSYS32/WindowsPowerShell/v1.0/powershell.exe
CHCP=$WINSYS32/chcp.com
PIDFILE=/var/run/dns-sync.pid
CACHE_PATH=/var/cache/dns-sync
if ! [ -d "${CACHE_PATH}" ] ; then
mkdir -p "${CACHE_PATH}" || exit 2
fi
linux_powershell() {
if [ -z "${__oemcp}" ] ; then
__oemcp=$(reg.exe query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage" /v OEMCP 2>&1 | sed -n 3p | tr -d '\015' | grep -o '[[:digit:]]*')
fi
$CHCP $__oemcp >/dev/null
$PS "$@" | tr -d '\015'
$CHCP 65001 >/dev/null
}
do_start () {
touch "${CACHE_PATH}/ns.current" "${CACHE_PATH}/search.current"
while true
do
UNIQUE_SEARCH=()
UNIQUE_NS=()
# Retrieve nameservers from via Powershell
if linux_powershell -Command "Get-DnsClientServerAddress -AddressFamily IPv4 | Select-Object -ExpandProperty ServerAddresses" | awk '!x[$0]++' > "${CACHE_PATH}/ns.new" ; then
if ! cmp -s "${CACHE_PATH}/ns.current" "${CACHE_PATH}/ns.new" ; then
mapfile -t UNIQUE_NS < "${CACHE_PATH}/ns.new"
linux_powershell -Command "Get-DnsClientGlobalSetting | Select-Object -ExpandProperty SuffixSearchList" > "${CACHE_PATH}/search.new" | awk '!s[$0]++' > "${CACHE_PATH}/search.new"
if ! cmp -s "${CACHE_PATH}/search.current" "${CACHE_PATH}/search.new" ; then
mapfile -t UNIQUE_SEARCH < "${CACHE_PATH}/search.new"
fi
cp -f /etc/resolv.conf "${CACHE_PATH}/resolv.conf"
if [ ${#UNIQUE_NS[@]} -gt 0 ] ; then
sed -i '/^nameserver.*/d' "${CACHE_PATH}/resolv.conf"
for i in "${UNIQUE_NS[@]}" ; do
echo "nameserver ${i}" >> "${CACHE_PATH}/resolv.conf"
done
mv -vf "${CACHE_PATH}/ns.new" "${CACHE_PATH}/ns.current"
fi
if [ ${#UNIQUE_SEARCH[@]} -gt 0 ] ; then
sed -i '/^search.*/d' "${CACHE_PATH}/resolv.conf"
echo "search ${UNIQUE_SEARCH[@]}" >> "${CACHE_PATH}/resolv.conf"
mv -vf "${CACHE_PATH}/search.new" "${CACHE_PATH}/search.current"
fi
if ! cmp -s "${CACHE_PATH}/resolv.conf" /etc/resolv.conf ; then
cp -f "${CACHE_PATH}/resolv.conf" /etc/resolv.conf
fi
fi
fi
sleep 30
done
}
do_status () {
PID=$(cat /var/run/dns-sync.pid 2>/dev/null)
if [ "$PID" == "" ]; then
echo "dns-sync is not running"
return
fi
if ps -p $PID > /dev/null
then
echo "dns-sync is running"
else
echo "dns-sync is not running"
fi
}
case "$1" in
start|"")
kill $(cat "${PIDFILE}" >/dev/null 2>&1) > /dev/null 2>&1 || true
do_start &
echo $! > "${PIDFILE}"
;;
restart|reload|force-reload)
stop && start
;;
stop)
PID=$(cat "${PIDFILE}")
if [ -r "/proc/${PID}/cmdline" ] ; then
kill $(cat "${PIDFILE}")
echo "dns-sync stopped"
rm -f "${PIDFILE}"
else
echo "dns-sync is not running"
fi
;;
status)
do_status
exit $?
;;
*)
echo "Usage: dns-sync.sh [start|stop]" >&2
exit 3
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment