linux系统怎么过滤ip
linux系统怎么过滤ip详细介绍
在 Linux 系统中过滤 IP 通常用于防火墙规则、日志分析或实时流量监控,以下是几种常见场景和对应方法:
一、防火墙规则过滤(推荐)
1.
iptables(传统防火墙)
- 拒绝特定 IP 所有流量(需
root权限):bashiptables INPUT .1.100 DROPiptables OUTPUT .1.100 DROP
- 允许 / 禁止特定端口 + IP:bash
iptables INPUT tcp .1.100 REJECT - 永久保存规则(避免重启失效):bash
iptables-save /etc/iptables/rules.v4systemctl iptables
2.
nftables(新一代防火墙,替代 iptables)
bash
nft rule filter input saddr .1.100 dropnft list ruleset
nft save /etc/nftables.conf
二、实时流量过滤(抓包工具)
1.
tcpdump 过滤指定 IP 流量
bash
tcpdump eth0 .1.100tcpdump any
2.
ss 查看当前连接的 IP
bash
ss
三、日志文件中提取 IP(如攻击记录)
1.
从 /var/log/fail2ban 过滤爆破 IP
bash
/var/log/fail2ban.log
2.
过滤 Nginx 日志中的异常 IP
bash
/var/log/nginx/access.log
四、常用场景总结
| 场景 | 工具推荐 | 命令示例 |
|---|---|---|
| 防火墙拦截恶意 IP | iptables/nftables | sudo iptables -A INPUT -s 恶意IP -j DROP |
| 实时监控特定 IP 流量 | tcpdump | tcpdump host 目标IP |
| 分析日志中的异常 IP | grep + awk | 从日志文件提取并统计 IP |
注意:修改防火墙规则前建议先测试,避免封禁管理 IP 导致失联。对于云服务器,还需结合云厂商的安全组规则(如 AWS Security Groups)。