Skip to content

Instantly share code, notes, and snippets.

@joshuar
Last active December 27, 2020 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joshuar/1b367102a787d8a35ecd to your computer and use it in GitHub Desktop.
Save joshuar/1b367102a787d8a35ecd to your computer and use it in GitHub Desktop.
Quick script to enable connection sharing (i.e. nat) on an interface in Linux. Based on http://xmodulo.com/2014/06/internet-connection-sharing-iptables-linux.html
#!/bin/bash
while getopts "i:t:" opt; do
case $opt in
i)
$(ip link show $OPTARG 1> /dev/null 2>&1)
if [[ $? != 0 ]]; then
echo "Argument to -${opt} should be an network device."
exit -1
else
interface=$OPTARG
fi
;;
t)
if [[ $OPTARG != 'on' ]] && [[ $OPTARG != 'off' ]]; then
echo "Need to select either 'on' or 'off'."
exit -1
else
toggle=$OPTARG
fi
;;
\?)
echo "Invalid option: -$OPTARG" >&2
;;
esac
done
# Get/update cached sudo credentials
sudo -v
## Internet connection shating script
case $toggle in
on)
sudo -n sysctl -q -w net.ipv4.ip_forward=1
sudo -n iptables -X
sudo -n iptables -F
sudo -n iptables -t nat -X
sudo -n iptables -t nat -F
sudo -n iptables -I INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
sudo -n iptables -I FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
sudo -n iptables -t nat -I POSTROUTING -o $interface -j MASQUERADE
;;
off)
sudo -n sysctl -q -w net.ipv4.ip_forward=0
sudo -n iptables -X
sudo -n iptables -F
sudo -n iptables -t nat -X
sudo -n iptables -t nat -F
;;
esac
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment