Skip to content

Instantly share code, notes, and snippets.

@nucther
Last active July 20, 2024 10:55
Show Gist options
  • Save nucther/ad75f901bdb2ba7225183b945a0b610b to your computer and use it in GitHub Desktop.
Save nucther/ad75f901bdb2ba7225183b945a0b610b to your computer and use it in GitHub Desktop.
Bash script for portforwarding using IP Tables. required `whois`, `iptables`
MySQL 3306 172.16.1.6:3306
OpenWRT 7000 172.16.1.7:80
#!/bin/bash
f_s='.services'
services=()
while IFS= read -r line
do
s=$(echo $line | awk '{print $1}')
services[${#services[@]}]="$s"
done < "$f_s"
text_help(){
echo -e "usage: ./portforwarding [options]"
echo -e "\t-a [IP Address]\tAdd permission to selected IP"
echo -e "\t-d\t\tDelete permission"
}
add(){
n=1
for service in ${services[@]}; do
echo -e "[ $n ] $service"
n=$((n + 1))
done
read -p "Please select service number you want to forward for $1? [ 1 ] " num_service
selected=($(cat $f_s | grep ${services[$num_service-1]}))
r_ip=($(whois -h bgp.tools $1 | tail -n 1 | awk -F '|' '{print $4}'))
if [ -n "$r_ip" ]; then
iptables -t nat -A PREROUTING -s $1 -p tcp -m tcp -m comment --comment "$1-${selected[0]}" --dport ${selected[1]} -j DNAT --to ${selected[2]}
echo "$r_ip $1 ${selected[0]}" >> $HOME/.allowed_ips
echo -e "\nSuccess added $1 with country id $r_id\n\n"
else
echo -e "\nFailed added $1\n\n"
fi
exit
}
delete(){
printf " ID \t%2s\t%15s\t%s\n" "Country" "IP Address" "Service"
did=()
n=1
while IFS= read -r line
do
tip=($(echo $line))
did[${#did[@]}]="${tip[1]}-${tip[2]}"
printf "[%2s ]\t%2s\t%15s\t%s\n" $n ${tip[0]} ${tip[1]} ${tip[2]}
n=$((n + 1))
done < $HOME/.allowed_ips
echo -e "\n\n"
read -p "Select IP to be deleted? [1] " s_ip
if [ -z "${did[$s_ip-1]}" ]; then
echo -e "\nPlease select correct number.\n\n"
exit
fi
tables=$(iptables -t nat -S | grep ${did[$s_ip-1]} | sed 's/\-A/\-D/')
eval "iptables -t nat $tables"
if [ -n "$tables" ]; then
ip_del=$(echo "${did[$s_ip-1]}" | awk -F '-' '{print $1" "$2}')
eval "sed -i '/$ip_del/d' $HOME/.allowed_ips"
echo -e "\nSuccess Delete \"$ip_del\"\n\n"
fi
exit
}
if [ -z "$1" ]; then
text_help
fi
while [ -n "$1" ]; do
case "${1}" in
-a)
if [ -z "$2" ]; then text_help;exit; fi
add $2;;
-d)
delete;;
*)
text_help;;
esac
shift
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment