• Welcome to LiuJason's Blog!

使用iptables的NAT表进行批量端口映射|脚本

Linux笔记 Jason 5 years ago (2019-05-26) 1252 Views 0 Comments QR code of this page

内网ip 172.27.2.1
虚拟机网络172.27.2.0/24
内网访问示例,如访问ip为172.27.2.101的虚拟机,
远程桌面 172.27.2.1:62101
vnc 172.27.2.1:62201

#!/bin/bash
#该shell为linux下创建windows虚拟机,使用linux作为网关时,批量端口映射
#vnc端口映射
let vncport=62201        #网关vnc初始端口,每循环一次加1
let deskport=62101       #网关远程桌面初始端口,每循环一次加1
let ipnum=101            #windows初始ip末位,每循环一次加1
let ipstop=199           #windows终止ip末位
pub_ip=172.27.2.1       #网关ip
nat_ip=172.27.2      #windows私有ip段
nat_vnc_port=5900       #windowsvnc端口
nat_mstsc_port=3389     #windows远程桌面端口
#iptables -t nat -A POSTROUTING -d $nat_ip.0/24 -p tcp --dport 5900 -j SNAT --to-source $nat_ip.1
#iptables -t nat -A POSTROUTING -d $nat_ip.0/24 -p tcp --dport 3389 -j SNAT --to-source $nat_ip.1
sudo grep net.ipv4.ip_forward=1 /etc/sysctl.conf 
if [ $? -ne 0 ]
then
    sudo echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
    sudo sysctl -p
fi
sudo iptables -t nat -F
sudo iptables -t nat -A POSTROUTING -j MASQUERADE
sudo echo -e "端口映射情况如下:\nwindows的ip地址\t\tvnc登录地址\t\t远程桌面登录地址"
while [ $ipnum -le $ipstop ];do
#vnc端口映射
sudo iptables -t nat -A PREROUTING -d $pub_ip -p tcp  --dport $vncport -j DNAT --to-destination $nat_ip.$ipnum:$nat_vnc_port
#远程桌面端口映射
sudo iptables -t nat -A PREROUTING -d $pub_ip -p tcp  --dport $deskport -j DNAT --to-destination $nat_ip.$ipnum:$nat_mstsc_port
sudo echo -e "$nat_ip.$ipnum\t\t$pub_ip:$vncport\t\t$pub_ip:$deskport"
let vncport=vncport+1
let deskport=deskport+1
let ipnum=ipnum+1
done
sudo echo -e "help:\niptabes -t nat -vnL --line-number\t查看映射表\niptables -t nat -F\t清空映射表"
sudo echo -e "iptables -t nat -D PREROUTING [序号]\t删除PREROUTING第【序号】条规则"
sudo echo -e "iptables -t nat -D POSTROUTING [序号]\t删除POSTROUTING第【序号】条规则"

执行结果

[root@master ~]# sh test.sh 
net.ipv4.ip_forward=1
端口映射情况如下:
windows的ip地址        vnc登录地址         远程桌面登录地址
192.168.10.20       10.199.2.12:7020        10.199.2.12:6020
192.168.10.21       10.199.2.12:7021        10.199.2.12:6021
192.168.10.22       10.199.2.12:7022        10.199.2.12:6022
192.168.10.23       10.199.2.12:7023        10.199.2.12:6023
192.168.10.24       10.199.2.12:7024        10.199.2.12:6024
192.168.10.25       10.199.2.12:7025        10.199.2.12:6025
help:
iptabes -t nat -vnL --line-number   查看映射表
iptables -t nat -F  清空映射表
iptables -t nat -D PREROUTING [序号]  删除PREROUTING第【序号】条规则
iptables -t nat -D POSTROUTING [序号] 删除POSTROUTING第【序号】条规则

This article is under CC BY-NC-SA 4.0 license.
Please quote the original link:https://www.liujason.com/article/282.html
Like (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址