Skip to content

Instantly share code, notes, and snippets.

@eznix86
Created June 11, 2025 20:30
Show Gist options
  • Select an option

  • Save eznix86/4b562aeafd99a0ad4479bba13e6dee31 to your computer and use it in GitHub Desktop.

Select an option

Save eznix86/4b562aeafd99a0ad4479bba13e6dee31 to your computer and use it in GitHub Desktop.
#!/bin/bash
set -e
if [[ $EUID -ne 0 ]]; then
echo "[ERROR] This script must be run as root (use sudo)." >&2
exit 1
fi
SUBNET="192.168.42."
echo "[INFO] Detecting host IP in subnet $SUBNET using arp -a..."
HOST_IP=$(arp -a | grep "$SUBNET" | awk '{print $2}' | tr -d '()' | head -n1)
if [[ -z "$HOST_IP" ]]; then
echo "[ERROR] Could not find host IP in subnet $SUBNET." >&2
exit 1
fi
echo "[INFO] Host IP detected as $HOST_IP"
echo "[INFO] SSH into host ($HOST_IP) to enable IP forwarding and iptables rules..."
ssh root@"$HOST_IP" bash -s <<EOF
set -e
echo "[HOST] Enabling IP forwarding..."
sysctl -w net.ipv4.ip_forward=1 >/dev/null
if [[ \$(sysctl -n net.ipv4.ip_forward) -ne 1 ]]; then
echo "[HOST ERROR] Failed to enable IP forwarding." >&2
exit 1
fi
OUT_IF=\$(ip route get 8.8.8.8 2>/dev/null | awk '{print \$5; exit}')
if [[ -z "\$OUT_IF" ]]; then
echo "[HOST ERROR] Could not detect outgoing interface." >&2
exit 1
fi
echo "[HOST] Outgoing interface detected: \$OUT_IF"
echo "[HOST] Setting iptables rules..."
iptables -P FORWARD ACCEPT
iptables -t nat -C POSTROUTING -s 192.168.42.0/24 -o "\$OUT_IF" -j MASQUERADE 2>/dev/null \
|| iptables -t nat -A POSTROUTING -s 192.168.42.0/24 -o "\$OUT_IF" -j MASQUERADE
if ! iptables -t nat -L POSTROUTING -n | grep -q MASQUERADE; then
echo "[HOST ERROR] iptables MASQUERADE rule was not set correctly." >&2
exit 1
fi
echo "[HOST] IP forwarding and NAT setup complete."
EOF
echo "[INFO] Setting default route on Milk-V Duo to host $HOST_IP..."
ip route replace default via "$HOST_IP"
echo "[INFO] Setting DNS on Milk-V Duo..."
echo "nameserver 8.8.8.8" >> /etc/resolv.conf
echo "[INFO] Testing connectivity from Milk-V Duo..."
if ping -c 2 -W 2 8.8.8.8 >/dev/null; then
echo "[SUCCESS] Milk-V Duo can reach 8.8.8.8"
if ping -c 2 -W 2 google.com >/dev/null; then
echo "[SUCCESS] DNS resolution works (google.com reachable)"
else
echo "[WARNING] DNS resolution failed, but IP connectivity works."
fi
else
echo "[ERROR] Milk-V Duo cannot reach the internet via host." >&2
exit 1
fi
@eznix86
Copy link
Author

eznix86 commented Jun 11, 2025

if time is an issue append the script with:

echo "Syncing time with NTP..."
ntpd -d -q -n -p pool.ntp.org
echo "Time sync completed"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment