Skip to content

Instantly share code, notes, and snippets.

@jimlinntu
Created January 7, 2021 06:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimlinntu/d34ed8d35245492cff4153e7a54a3a6a to your computer and use it in GitHub Desktop.
Save jimlinntu/d34ed8d35245492cff4153e7a54a3a6a to your computer and use it in GitHub Desktop.
add_masquerade.sh
#!/bin/bash
interface=ipsec_bridge
target_ip="192.168.2.100"
cidr_ip=$(ip addr show "$interface" | grep 'inet ' | awk '{print $2}')
network=$(ipcalc "$cidr_ip" | grep "Network:" | awk '{print $2}')
function add_masquerade {
iptables -t nat -C POSTROUTING -s "$network" -j SNAT --to "$target_ip" || {
iptables -t nat -I POSTROUTING 1 -s "$network" -j SNAT --to "$target_ip"
}
}
function clear_masquerade {
iptables -t nat -C POSTROUTING -s "$network" -j SNAT --to "$target_ip" && {
iptables -t nat -D POSTROUTING -s "$network" -j SNAT --to "$target_ip"
}
}
echo "Prepare to add NAT source network from $network to $target_ip"
add_masquerade
echo "Insert a source NAT rule in front of POSTROUTING chain...."
echo "Done!"
# Install signal handlers
trap "clear_masquerade" SIGINT SIGTERM
sleep infinity &
# wait for SIGINT or SIGTERM
wait
echo "Gracefully shutdown!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment