大网数据广告活动
服务器运维问答

iptables: checking if a IP is blocked in firewall

· 52CE 我爱测

If a IP is blocked in iptables by its "IP" it is easy to grep iptables like iptables -L -n | grep "a.b.c.d" but if the IP has been blocked using a IP range like : iptables -A INPUT -s "163.172.000.000/16" -j DROP well, then this …

问题原文

原帖链接 · Max Muster · CC BY-SA 4.0

If a IP is blocked in iptables by its "IP" it is easy to grep iptables like

iptables -L -n | grep "a.b.c.d"

but if the IP has been blocked using a IP range like :

iptables -A INPUT -s "163.172.000.000/16" -j DROP

well, then this method does not work any more. what method could be used?

已采纳解答

原帖链接 · Eduardo Trápani · CC BY-SA 4.0

You could use ipaddr with python.

First you list the rules you are interested in with iptables -S (that will list single IPs as /32, which comes in handy):

Then you feed the blocks to this python script, check_ip.py. It checks if the first parameter (the address) belongs to the second parameter (the block) and exits with code 0 or 1.

#!/bin/python3

import ipaddress
import sys

sys.exit(ipaddress.ip_address(sys.argv[1]) in ipaddress.ip_network(sys.argv[2],strict=False))

You can then connect those two pieces.

The following is a quickly written bash command line, but you could also move the whole code to python, or use xargs, ...

iptables -S | grep DROP | awk '{print $4,$0}' | while read a b; do python3 check_ip.py IP.ADDR.TO.CHECK $a || echo $b; done

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2020-02-26)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。