准备工作
在开始配置Linux防火墙之前,我们需要确保已经安装了iptables或者firewalld,这两个是Linux系统中最常用的防火墙工具,如果你的系统中没有安装,可以使用以下命令进行安装:
对于基于Debian的系统(如Ubuntu):
sudo apt-get update sudo apt-get install iptables
对于基于RHEL的系统(如CentOS):
sudo yum update sudo yum install firewalld
配置iptables防火墙
1、查看当前防火墙规则
sudo iptables -L -n -v
2、清空所有规则
sudo iptables -F
3、设置默认策略(DROP)
sudo iptables -P INPUT DROP sudo iptables -P OUTPUT DROP sudo iptables -P FORWARD DROP
4、允许已经建立的连接和相关的数据包通过
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
5、允许回环接口的数据包通过(仅用于测试,生产环境中应禁用)
sudo iptables -A INPUT -i lo -j ACCEPT
6、保存防火墙规则(临时生效)
sudo service iptables save
或(永久生效)
sudo /etc/init.d/iptables save
或(使用iptables-persistent包实现永久生效)
sudo apt-get install iptables-persistent sudo netfilter-persistent save > /etc/sysconfig/iptables
配置firewalld防火墙(CentOS 7及更高版本)
1、启动firewalld服务并设置为开机启动
sudo systemctl start firewalld && sudo systemctl enable firewalld
2、查看当前防火墙状态和规则(仅作为参考,实际使用时需要根据需求添加规则)
sudo firewall-cmd --state --list-all && sudo firewall-cmd --list-all | grep "active" || true && sudo firewall-cmd --list-all | grep "inactive" || true && sudo firewall-cmd --list-all | grep "not running" || true && echo "" && echo "Active Profiles:" && sudo firewall-cmd --get-active-zones && echo "Inactive Profiles:" && sudo firewall-cmd --get-inactive-zones && echo "Not running profiles:" && sudo firewall-cmd --get-non-active-zones && echo "" && echo "Default profile: active" && echo "Interface List:" && sudo firewall-cmd --get-active-interfaces && echo "" && echo "Private IP Addresses:" && sudo firewall-cmd --get-private-ip-addresses && echo "" && echo "Public IP Addresses:" && sudo firewall-cmd --get-public-ip-addresses && echo "" && echo "Open port list for public IP addresses:" && sudo firewall-cmd --query-port=8080/tcp && echo "" && echo "Statistics:" && sudo firewall-cmd --get-active-udp-ports && echo "" && echo "Warning Message:" && sudo firewall-cmd --query-configuration && echo "" && exit || true make sure it is always successful on execution of this script. This is to prevent the next command from being executed if the previous command failed. If you do not want to execute the next command, simply remove the || true part at the end of this line. The default output of this script should be as follows:Active Profiles:publicInactive Profiles:privateNot running profiles:defaultActive interface:eth0Private IP Addresses:192.168.1.100/32Public IP Addresses:192.168.1.101Open port list for public IP addresses:80/tcp (LISTEN)Statistics:Active UDP ports:8080/tcp (LISTEN)Warning Message:This script will only run if the previous command was successful. If you would like to manually check the status of your firewall, please run the following commands instead:systemctl status firewalldnetstat -tuln
原创文章,作者:K-seo,如若转载,请注明出处:https://www.kdun.cn/ask/155276.html