利用iptables做端口转发

#!/bin/bash

#sh forward_port.sh add/del  port
#sh forward_port.sh add  80

if [ -z  $1 ];then
  echo "参数1为空"
elif [ -z  $2 ];then
  echo "参数2为空"
fi

mode=$1
pro='tcp'
#src_host='47.97.205.48'
src_host='47.97.205.48'
src_port=$2
Dst_Host='183.129.207.71'
Dst_Port=$2

# 清空规则
function clean_rule(){
iptables -F
iptables -X
iptables -Z
iptables -t nat -F
}
function add_rule(){
#iptables -w -t nat -A PREROUTING  -p $pro -d $src_host  --dport $src_port -j DNAT --to $Dst_Host:$Dst_Port
echo "iptables -t nat -A PREROUTING  -p $pro -d $src_host  --dport $src_port -j DNAT --to $Dst_Host:$Dst_Port"
#iptables -w -t nat -A POSTROUTING -p $pro -d $Dst_Host --dport $Dst_Port -j SNAT --to $src_host
echo "iptables -t nat -A POSTROUTING -p $pro -d $Dst_Host --dport $Dst_Port -j SNAT --to $src_host"
}

function del_rule(){
iptables -w -t nat -D PREROUTING  -p $pro -d $src_host  --dport $src_port -j DNAT --to $Dst_Host:$Dst_Port
#echo "iptables -t nat -A PREROUTING  -p $pro -d $src_host1  --dport $src_port -j DNAT --to $Dst_Host:$Dst_Port"
iptables -w -t nat -D POSTROUTING -p $pro -d $Dst_Host --dport $Dst_Port -j SNAT --to $src_host
#echo "iptables -t nat -A POSTROUTING -p $pro -d $Dst_Host --dport $Dst_Port -j SNAT --to $src_host1"
}

if [[ "$mode" == "add"  ]];then
  add_rule
elif [[ "$mode" == "del"  ]];then
  del_rule
else
  echo "参数1不正确(add/del)"
fi

iptables-save > /dev/null 


# 显示已有规则
#iptables -t nat -L -n --line-number

猜你喜欢

转载自www.cnblogs.com/vijayfly/p/9257911.html
今日推荐