#!/bin/bash chan=$1 chan_pre=$chan'_pre' chan_forward=$chan'_forward' chan_post=$chan'_post' from=$2 from_port=$3 to=$4 to_port=$5 if ! [ -n "$1" ]; then echo "iptable chan not found" >&1 exit 1 fi if ! [ -n "$2" ]; then echo "from host not found" >&1 exit 1 fi if ! [ -n "$3" ]; then echo "from port not found" >&1 exit 1 fi if ! [ -n "$4" ]; then echo "destination host not found" >&1 exit 1 fi if ! [ -n "$5" ]; then echo "destination port not found" >&1 exit 1 fi echo "redirect ${from}:${from_port} to ${to}:${to_port}" ## 清空 引用 sudo iptables -t nat -nvL PREROUTING --line-number | awk -F ' ' 'BEGIN{c=0} /'${chan_pre}'/ {printf "%s %s %s\n",c, $1,$4;system("sudo iptables -t nat -D PREROUTING "$1-c);c++}' sudo iptables -t filter -nvL FORWARD --line-number | awk -F ' ' 'BEGIN{c=0} /'${chan_forward}'/ {printf "%s %s %s\n",c, $1,$4;system("sudo iptables -t filter -D FORWARD "$1-c);c++}' sudo iptables -t nat -nvL POSTROUTING --line-number | awk -F ' ' 'BEGIN{c=0} /'${chan_post}'/ {printf "%s %s %s\n",c, $1,$4;system("sudo iptables -t nat -D POSTROUTING "$1-c);c++}' ## 清空自定义链 sudo iptables -t nat -F $chan_pre sudo iptables -t filter -F $chan_forward sudo iptables -t nat -F $chan_post ## 删除自定义链 sudo iptables -t nat -X $chan_pre sudo iptables -t filter -X $chan_forward sudo iptables -t nat -X $chan_post ## 创建自定义链 sudo iptables -t nat -N $chan_pre sudo iptables -t filter -N $chan_forward sudo iptables -t nat -N $chan_post sudo iptables -t nat -p tcp -d $from --dport $from_port -j DNAT --to $to:$to_port -I $chan_pre sudo iptables -t nat -p udp -d $from --dport $from_port -j DNAT --to $to:$to_port -I $chan_pre sudo iptables -t filter -d $to -j ACCEPT -I $chan_forward sudo iptables -t nat -p tcp -d $to --dport $to_port -j SNAT --to $from -I $chan_post sudo iptables -t nat -p udp -d $to --dport $to_port -j SNAT --to $from -I $chan_post ## 引用新链 sudo iptables -t nat -I PREROUTING -j $chan_pre sudo iptables -t filter -I FORWARD -j $chan_forward sudo iptables -t nat -I POSTROUTING -j $chan_post #iptables -L sudo iptables -t nat -nvL $chan_pre --line-number sudo iptables -t nat -nvL PREROUTING --line-number echo "\n\n" sudo iptables -t filter -nvL $chan_forward --line-number sudo iptables -t filter -nvL FORWARD --line-number echo "\n\n" sudo iptables -t nat -nvL $chan_post --line-number sudo iptables -t nat -nvL POSTROUTING --line-number