Created
January 7, 2021 06:00
-
-
Save jimlinntu/d34ed8d35245492cff4153e7a54a3a6a to your computer and use it in GitHub Desktop.
add_masquerade.sh
This file contains 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
#!/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