简体   繁体   English

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

[英]How to use Python to put a CSV list of ips in iptables / IP Sets?

I would like to use this CSV file to block all IPs from the list. 我想使用此CSV文件来阻止列表中的所有IP。 The entries in the CSV file are IP ranges. CSV文件中的条目是IP范围。 How do I seperate the IP ranges from text, and add those IP ranges to the iptables with the rule to drop all connections with those IPs. 如何将IP范围与文本分开,并使用规则删除与这些IP的所有连接,将这些IP范围添加到iptables

Btw, I think this is better to use for large ip ranges, http://ipset.netfilter.org/index.html 顺便说一句,我认为最好将其用于较大的IP范围, http://ipset.netfilter.org/index.html

You will need python netaddr module for that 您将需要python netaddr模块

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])

maybe take a look at https://docs.python.org/3/library/ipaddress.html to manipulate your ip addresses. 也许看看https://docs.python.org/3/library/ipaddress.html来操纵您的IP地址。 ipaddress.summarize_address_range(first, last) could be nice to generate the iptables rule. ipaddress.summarize_address_range(first,last)可以很好地生成iptables规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM