Skip to content

Instantly share code, notes, and snippets.

@Shkarlatov
Last active December 21, 2025 12:23
Show Gist options
  • Select an option

  • Save Shkarlatov/ad83513d3ef26039ecd818922a57cb50 to your computer and use it in GitHub Desktop.

Select an option

Save Shkarlatov/ad83513d3ef26039ecd818922a57cb50 to your computer and use it in GitHub Desktop.
OpenVPN hotplug script for DNS management
ssh root@192.168.1.1 << 'SCRIPT_EOF'
cat << "EOF" > /etc/hotplug.d/openvpn/10-resolv
# /etc/hotplug.d/openvpn/10-resolv
# OpenVPN hotplug script for DNS management
LOG() {
logger -t openvpn-hotplug "$*"
}
CHANGE_DNS() {
LOG "DNS will be changed to $*"
uci set dhcp.@dnsmasq[0].resolvfile="$*"
service dnsmasq restart
LOG "Changed to: $(uci -q get dhcp.@dnsmasq[0].resolvfile)"
}
MONITORING() {
FAILURE_COUNT=0
FAILURE_MAX=5
while true; do
sleep 60
if /etc/init.d/openvpn status $INSTANCE 2>/dev/null | grep -q "inactive"; then
LOG "VPN $INSTANCE inactive. Exit"
exit 1
fi
if ping -c 1 -W 5 -I $dev $remote_1 >/dev/null 2>&1; then
FAILURE_COUNT=0
LOG "VPN $INSTANCE still alive!"
else
FAILURE_COUNT=$((FAILURE_COUNT + 1))
LOG "Ping failed. Consecutive failures: $FAILURE_COUNT"
if [ $FAILURE_COUNT -ge $FAILURE_MAX ]; then
LOG "VPN connection lost. Stopping openvpn service"
service openvpn stop
exit 1
fi
fi
done
}
case "$ACTION" in
up)
LOG "VPN $INSTANCE connected, configuring DNS"
RES_FILE="$(uci -q get dhcp.@dnsmasq[0].resolvfile)"
VPN_RES_FILE="${RES_FILE%.*}.vpn"
env | sed -n -e "
/^foreign_option_.*=dhcp-option.*DNS/s//nameserver/p
/^foreign_option_.*=dhcp-option.*DOMAIN/s//search/p
" | sort -u > "$VPN_RES_FILE"
# Fallback to .auto if no DNS servers received
if ! grep -q "nameserver" "${RES_FILE%.*}.vpn" 2>/dev/null; then
LOG "No DNS from VPN $INSTANCE, using auto configuration"
exit 0
fi
CHANGE_DNS "$VPN_RES_FILE"
export ACTION=monitoring
/etc/hotplug.d/openvpn/10-resolv &
pid=$!
echo $pid > /tmp/monitoring.pid
;;
down)
LOG "VPN $INSTANCE disconnected, restoring DNS"
RES_FILE="$(uci -q get dhcp.@dnsmasq[0].resolvfile)"
CHANGE_DNS "${RES_FILE%.*}.auto"
pid=$(cat /tmp/monitoring.pid)
kill $pid
rm -f /tmp/monitoring.pid
;;
monitoring)
LOG "Running monitoring on $remote_1"
MONITORING
;;
esac
EOF
grep -q "^/etc/hotplug.d/openvpn/10-resolv$" /etc/sysupgrade.conf || echo "/etc/hotplug.d/openvpn/10-resolv" >> /etc/sysupgrade.conf
SCRIPT_EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment