sudo apt-get install ufw
提示:除开精简版一般云提供商LTS版本(18/22LTS)都是默认安装的。
sudo ufw status
Status: inactive
返回为inactive则为未启动防火墙。
如果你是xshell等shell工具远程连接的服务器,则建议先添加以下规则,开放22端口
$ sudo ufw allow 22
启用防火墙
$ sudo ufw enable
Command may disrupt existing ssh connections. Proceed with operation (y|n)?
命令可能会中断现有的ssh连接。继续操作(y|n)?
因为是在远程的Xshell进行连接开启防火墙的,有的系统是没有将SSH的22端口设置为public的,所以会有这样的提示,这里分为两种情况,如果开启防火墙时在防火墙之中检测到22端口已添加为防火墙的开放端口,那么输入y继续操作以后,当前Xshell会自动断开连接;相反,如果开启防火墙时在防火墙之中没有检测到22端口,那么输入y继续操作以后22端口将会不再支持其他连接,只支持当前已有的这个连接,保持当前连接的原因是可以通过该连接开放22端口。
启用后再次查看状态
root@dev:~# sudo ufw status
Status: active
To Action From
-- ------ ----
22 ALLOW Anywhere
22 (v6) ALLOW Anywhere (v6)
详细信息查看
sudo ufw status verbose
root@dev:~# sudo ufw status verbose
Status: active
Logging: on (low)
Default: allow (incoming), allow (outgoing), deny (routed)
New profiles: skip
To Action From
-- ------ ----
22 ALLOW IN Anywhere
22 (v6) ALLOW IN Anywhere (v6)
设置默认入站/出站规则
Default: allow (incoming), allow (outgoing), deny (routed)
解释:
默认:允许(入栈),允许(出栈),拒绝(路由)
修改为:入栈默认禁用,出允许
sudo ufw default deny incoming sudo ufw default allow outgoing
开放,允许所有来源访问80端口
sudo ufw allow 80
设置后需要重载配置生效【提示:有些Ubuntu版本可以不用reload添加后即时生效】
sudo ufw reload
查看
root@dev:~# sudo ufw status
Status: active
To Action From
-- ------ ----
22 ALLOW Anywhere
80 ALLOW Anywhere
22 (v6) ALLOW Anywhere (v6)
80 (v6) ALLOW Anywhere (v6)
关闭/删除端口(按规则删除)
sudo ufw delete allow 80
或者按规则编号
root@dev:~# sudo ufw status numbered
Status: active
To Action From
-- ------ ----
[ 1] 22 ALLOW IN Anywhere
[ 2] 22 (v6) ALLOW IN Anywhere (v6)
root@dev:~#
然后根据前面的规则号码删除
sudo ufw delete 2
开放端口
sudo ufw allow 801/tcp
查看
root@dev:~# sudo ufw reload
Firewall reloaded
root@dev:~# sudo ufw status
Status: active
To Action From
-- ------ ----
22 ALLOW Anywhere
80 ALLOW Anywhere
801/tcp ALLOW Anywhere
22 (v6) ALLOW Anywhere (v6)
80 (v6) ALLOW Anywhere (v6)
801/tcp (v6) ALLOW Anywhere (v6)
关闭/删除端口
sudo ufw delete allow 801/tcp
开放
sudo ufw allow from 192.168.1.12 to any port 3306
查看
root@dev:~# sudo ufw status
Status: active
To Action From
-- ------ ----
22 ALLOW Anywhere
80 ALLOW Anywhere
3306 ALLOW 192.168.1.12
22 (v6) ALLOW Anywhere (v6)
80 (v6) ALLOW Anywhere (v6)
删除
sudo ufw delete allow from 192.168.1.12 to any port 3306
开放
sudo ufw allow from 192.168.1.11
查看
root@dev:~# sudo ufw status
Status: active
To Action From
-- ------ ----
22 ALLOW Anywhere
80 ALLOW Anywhere
Anywhere ALLOW 192.168.1.11
22 (v6) ALLOW Anywhere (v6)
80 (v6) ALLOW Anywhere (v6)
关闭
sudo ufw delete allow from 192.168.1.11
sudo ufw disable
sudo ufw reset
关联文章:
https://www.leftso.com/article/2411191551231548.html