在CentOS 7系统中,屏蔽特定IP地址是保障服务器安全、防止恶意访问或限制特定用户访问的常用操作,通过系统自带的防火墙工具或直接配置iptables,管理员可以高效实现IP屏蔽功能,本文将详细介绍两种主流方法及其操作步骤、注意事项,帮助用户根据实际需求选择合适的方案。

使用firewalld屏蔽IP(推荐方法)
CentOS 7默认采用firewalld作为防火墙管理工具,其动态管理特性适合大多数场景,屏蔽IP的步骤如下:
检查firewalld状态
首先确认firewalld服务是否运行:systemctl status firewalld
若未运行,可通过
systemctl start firewalld启动,并设置systemctl enable firewalld实现开机自启。添加IP屏蔽规则
使用rich rule语法精确屏蔽IP,例如屏蔽IP为168.1.100的地址:firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.100" reject'
参数说明:
--permanent:规则永久生效,需重启防火墙;family="ipv4":指定IPv4协议,若屏蔽IPv6则改为ipv6;reject:拒绝访问,也可用drop直接丢弃数据包(无响应)。
重新加载防火墙
执行以下命令使规则立即生效:
firewall-cmd --reload
验证规则是否添加成功:
firewall-cmd --list-rich-rules
删除屏蔽规则
若需解除屏蔽,通过以下命令移除规则:firewall-cmd --permanent --remove-rich-rule='rule family="ipv4" source address="192.168.1.100" reject'
使用iptables屏蔽IP(传统方法)
若系统未启用firewalld或习惯使用iptables,可通过以下步骤操作:
检查iptables服务
确认iptables已安装并运行:yum install iptables-services -y systemctl start iptables systemctl enable iptables
添加屏蔽规则
在INPUT链中添加规则,例如屏蔽IP168.1.100:iptables -I INPUT -s 192.168.1.100 -j DROP
参数说明:

-I INPUT:插入到INPUT链(入站规则);-s:指定源IP地址;-j DROP:丢弃数据包。
保存规则
iptables规则默认重启后失效,需手动保存:service iptables save
或使用
iptables-save > /etc/sysconfig/iptables导出配置。批量屏蔽IP
若需屏蔽多个IP,可先将IP写入文件(如ips.txt),再通过脚本批量添加:for ip in $(cat ips.txt); do iptables -I INPUT -s $ip -j DROP done service iptables save
注意事项
- 规则优先级:firewalld和iptables的规则按顺序匹配,建议将IP屏蔽规则置于较高优先级。
- 日志记录:为便于排查,可在屏蔽规则中添加日志(如
iptables -I INPUT -s 192.168.1.100 -j LOG --log-prefix "Blocked_IP:")。 - 误屏蔽处理:若屏蔽了重要IP,可通过
iptables -D INPUT -s [IP] -j DROP删除规则,或firewalld的--remove-rich-rule解除屏蔽。 - 性能影响:屏蔽大量IP时,建议使用
ipset工具提升效率,ipset create block_set hash:ip ipset add block_set 192.168.1.100 iptables -I INPUT -m set --match-set block_set src -j DROP
相关问答FAQs
Q1: 如何查看当前已屏蔽的IP列表?
A1:
- 若使用firewalld,执行
firewall-cmd --list-rich-rules | grep reject即可查看所有拒绝规则的IP; - 若使用iptables,运行
iptables -L INPUT --line-numbers -n | grep DROP,其中src列即为屏蔽的IP。
Q2: 屏蔽IP后,对方能否通过代理或VPN绕过限制?
A2:
无法完全绕过,屏蔽的是源IP地址,若对方通过代理或VPN更换IP,则需重新屏蔽新IP,若需彻底限制,可结合端口限制、地理位置屏蔽或应用层认证(如SSH密钥)等多重策略增强安全性。
【版权声明】:本站所有内容均来自网络,若无意侵犯到您的权利,请及时与我们联系将尽快删除相关内容!
发表回复