如何使用Python将IP的CSV列表放入iptables/IP集中?

2024-04-29 22:04:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用this CSV file阻止列表中的所有IP。CSV文件中的条目是IP范围。如何将IP范围从文本中分离出来,并使用删除与这些IP的所有连接的规则将这些IP范围添加到iptables。在

顺便说一句,我认为这更适合大ip范围,http://ipset.netfilter.org/index.html


Tags: 文件csvorg文本iphttpiptables列表
2条回答

也许可以看看https://docs.python.org/3/library/ipaddress.html来操纵你的ip地址。ipaddress.summary_地址范围(首先,最后一个)生成iptables规则可能很好。在

您将需要pythonnetaddr模块来实现这一点

import netaddr

with open('ipranges.txt','r') as f:
    for line in f:
        startip,endip=line.split(',')[:2]
        print 'iptables -I INPUT -s {} -j DROP'.format(netaddr.iprange_to_cidrs(startip, endip)[0])

相关问题 更多 >