Install ufw on linux to enable port forwarding

1. Installation

# debian ubuntu
apt-get install ufw
# centos
yum install ufw

2. Related commands

#查看防火墙规则 以及相关开启端口
ufw status
#开启防火墙
ufw enable 
#关闭防火墙
ufw disable
#重启防火墙
ufw reload
#开启指定tcp或者udp端口
ufw allow 22/tcp

#同时开启tcp与udp端口
ufw allow 445

#删除53端口
ufw delete allow 53

#拒绝指定tcp或者udp端口
allow/deny 20/tcp
allow/deny 20/udp

#ip访问所有端口
sudo ufw allow from 192.168.8.8

#开启指定范围端口
ufw allow proto tcp from any to any port 16300:32768

#删除指定范围端口
ufw delete allow proto udp from any to any port 16384:32768

#禁止某项规则
sudo ufw deny smtp

#删除某项规则
sudo ufw delete allow smtp

#外来访问默认允许
ufw default allow/deny

#允许HTTP流量(端口80 )
sudo ufw allow in on eth0 to any port 80

#允许MySQL数据库服务器(端口3306 )
sudo ufw allow in on eth1 to any port 3306

3. Configure port forwarding

3.1. Modify the configuration file

vim /etc/ufw/sysctl.conf

Remove the circled staple food
insert image description here
as follows and
insert image description here
execute the command to make it take effect

sysctl -p

3.2 Local port forwarding configuration

modify the rules,

vim /etc/ufw/before.rules

Before *filter, add the following paragraph

*nat
:PREROUTING ACCEPT [0:0]
-A PREROUTING -p tcp -m tcp -d from_ip --dport from_port -j DNAT --to-destination to_ip:to_port
-A POSTROUTING -j MASQUERADE
COMMIT

Please modify the from_ip, from_port, to_ip and to_port variables to actual values.
If you do not understand, please refer to iptables related documents.
as follows

*nat
:PREROUTING ACCEPT [0:0]

-A PREROUTING -p tcp --dport 8022 -j REDIRECT --to-port 22


-A PREROUTING -p tcp --dport 13389 -j DNAT --to-destination 192.168.199.185:3389
# PREROUTING链:在进行路由选择前处理数据包(做目标地址转换)
# 去往跳板机机 13389 端口的流量 转发 到内网的3389端口
 
 
-A POSTROUTING -p tcp -d 192.168.199.185 --dport 3389 -j SNAT --to-source 192.168.199.247
# POSTROUTING链:在进行路由选择后处理数据包(对数据链进行源地址修改转换)
# 去往内网 3389 端口的流量 修改源IP是跳板机

-A POSTROUTING -j MASQUERADE
COMMIT

3.3 Remote port forwarding configuration

Modify to circled part
insert image description here

3.4 start


ufw enable

service ufw start

service ufw restart

service ufw status

Note, remember to open the relevant port

Guess you like

Origin blog.csdn.net/god_sword_/article/details/128088728