簡體   English   中英

Python:從IP地址列表生成IP范圍

[英]Python: Generate IP ranges from list of IP addresses

我有一個.csv文件,其中包含一些數據中心的IP地址列表。 該列表當前看起來類似於下表:

  Data_Center_Name      IP
              DC_1      52.102.182.2
              DC_1      52.102.182.4
              DC_1      52.102.182.1
              DC_1      52.102.182.5
              DC_1      52.102.182.3
              DC_1      27.101.178.17
              DC_1      27.101.178.16
              DC_1      27.101.178.15
              DC_1      23.201.165.7
              DC_2      55.200.162.10
              DC_2      55.200.162.12
              DC_2      55.200.162.13
              DC_2      55.200.162.11
              DC_3      30.101.102.4

我想將列表轉換為單個列表,例如:

     DC_1 = [52.102.182.1-52.102.182.5,
             27.101.178.15-27.101.178.17,
             23.201.165.7]
     DC_2 = [55.200.162.10-55.200.162.13]
     DC_3 = [30.101.102.4]

誰能幫我使用python嗎?

*此答案已被編輯,導致粗心閱讀問題*

對於單個list范圍

df[['P1','P2']]=df.IP.str.rsplit('.',1).apply(pd.Series)
d=df.sort_values(['Data_Center_Name','P1','P2']).\
    groupby(['Data_Center_Name','P1']).\
       IP.apply(lambda x : x.iloc[0]+'-'+x.iloc[-1] if len(x)>1 else x.iloc[0] )
d
Out[388]: 
Data_Center_Name  P1        
DC_1              23.201.165                   23.201.165.7
                  27.101.178    27.101.178.15-27.101.178.17
                  50.102.182                   50.102.182.2
                  52.102.182      52.102.182.1-52.102.182.5
DC_2              55.200.162    55.200.162.10-55.200.162.13
DC_3              30.101.102                   30.101.102.4
Name: IP, dtype: object

為了得到你的結果

d.groupby(level=0).apply(list)
Out[392]: 
Data_Center_Name
DC_1    [23.201.165.7, 27.101.178.15-27.101.178.17, 50...
DC_2                        [55.200.162.10-55.200.162.13]
DC_3                                       [30.101.102.4]
Name: IP, dtype: object

我的解決方案是:

  1. 將每個IP轉換為十進制數

  2. 從列表編號排序並獲取范圍(間隔)

  3. 將它們轉換為IP格式。

輸入:

ips = [ "52.102.182.2", "52.102.182.4", "52.102.182.1", "52.102.182.5", "52.102.182.3", 
        "27.101.178.17", "27.101.178.16", "27.101.178.15",
        "23.201.165.7", ]

步驟1:

IP =>二進制=>十進制

# Convert ips to binary strings
bins = [''.join([bin(int(i))[2:].zfill(8) for i in ip.split('.')]) for ip in ips]

# Convert binary strings to decimal numbers
numbers = [int(b, 2) for b in bins]

或IP =>小數

# Convert ips to decimal numbers
numbers = [sum((256 ** (3 - k)) * int(n) for k, n in enumerate(ip.split('.'))) for ip in ips]

第2步:

# Sort decimal numbers
numbers.sort()

# Get ranges from decimal numbers
ranges = []
tmp = []
for i in range(len(numbers)):
    tmp.append(numbers[i])
    if (i == len(numbers) - 1) or (numbers[i + 1] > numbers[i] + 1):
        if len(tmp) == 1:
            ranges.append(tmp[0])
        else:
            ranges.append((tmp[0], tmp[-1]))
        tmp = []

第三步:

# Convert dec ranges to ip ranges
def dec_to_ip(n):
    return '.'.join([str(int(n % 256 ** (4 - k) / 256 ** (3 - k))) for k in range(4)])

# Final result
ip_ranges = [(dec_to_ip(r[0]), dec_to_ip(r[1])) if type(r) == tuple else dec_to_ip(r) for r in ranges]

輸出:

['23.201.165.7', ('27.101.178.15', '27.101.178.17'), ('52.102.182.1', '52.102.182.5')]

使用python3(如果需要,我可以使用python2)

利用ipaddressgroupby內置庫以及其他內置商品:

創建將ipaddress對象列表轉換為范圍的函數:

def create_range(ip_addresses):
    groups=[]
    for _, g in itertools.groupby(enumerate(sorted(ip_addresses)), lambda (i,x):i-int(x)):
       group = map(operator.itemgetter(1), g)
       if len(group) > 1:
           groups.append("{}-{}".format(group[0], str(group[-1]).split('.')[-1]))
       else:
           groups.append(str(group[0]))
    return groups

導入所需的庫,從csv中解析出值(使用StringIO模仿從文件中讀取):

import csv ## for reading csv file
import ipaddress ## for creating ip address objects
import io ## for mimicking reading csv file
import operator ## for grouping operation
import itertools ## for grouping operation
import collections ## for creating a defaultdict

ips = defaultdict(list)
csv_file = u"""Data_Center_Name,      IP
              DC_1,      50.102.182.2
              DC_1,      52.102.182.4
              DC_1,      52.102.182.1
              DC_1,      52.102.182.5
              DC_1,      52.102.182.3
              DC_1,      27.101.178.17
              DC_1,      27.101.178.16
              DC_1,      27.101.178.15
              DC_1,      23.201.165.7
              DC_2,      55.200.162.10
              DC_2,      55.200.162.12
              DC_2,      55.200.162.13
              DC_2,      55.200.162.11
              DC_3,      30.101.102.4
"""

with io.StringIO(csv_file) as f:
    reader = list(csv.reader(f))
    for (dc, ip) in reader[1:]:
        ip = ipaddress.IPv4Address(unicode(ip.strip()))
        ips[dc.strip()].append(ip)
    result = {dc: create_range(ip_range) for dc, ip_range in ips.items()}

結果:

In [92]: result
Out[92]:
{'DC_1': ['23.201.165.7',
  '27.101.178.15-17',
  '50.102.182.2',
  '52.102.182.1',
  '52.102.182.3-5'],
 'DC_2': ['55.200.162.10-13'],
 'DC_3': ['30.101.102.4']}

Python2

import csv ## for reading csv file
import ipaddress ## for creating ip address objects
from StringIO import StringIO  ## for mimicking reading csv file
import operator ## for grouping operation
import itertools ## for grouping operation
import collections ## for creating a defaultdict

def create_range(ip_addresses):
    groups=[]
    for _, g in itertools.groupby(enumerate(sorted(ip_addresses)), lambda (i,x):i-int(x)):
       group = map(operator.itemgetter(1), g)
       if len(group) > 1:
           groups.append("{}-{}".format(group[0], str(group[-1]).split('.')[-1]))
       else:
           groups.append(str(group[0]))
    return groups

ips = collections.defaultdict(list)

csv_file = """Data_Center_Name,      IP
              DC_1,      50.102.182.2
              DC_1,      52.102.182.4
              DC_1,      52.102.182.1
              DC_1,      52.102.182.5
              DC_1,      52.102.182.3
              DC_1,      27.101.178.17
              DC_1,      27.101.178.16
              DC_1,      27.101.178.15
              DC_1,      23.201.165.7
              DC_2,      55.200.162.10
              DC_2,      55.200.162.12
              DC_2,      55.200.162.13
              DC_2,      55.200.162.11
              DC_3,      30.101.102.4
"""

reader = csv.reader(StringIO(csv_file))
next(reader)
for (dc, ip) in reader:
    ip = ipaddress.IPv4Address(unicode(ip.strip()))
    ips[dc.strip()].append(ip)
result = {dc: create_range(ip_range) for dc, ip_range in ips.items()}

py2代碼的結果

print result
{'DC_2': ['55.200.162.10-13'], 'DC_3': ['30.101.102.4'], 'DC_1': ['23.201.165.7', '27.101.178.15-17', '50.102.182.2', '52.102.182.1', '52.102.182.3-5']}

做得好! 謝謝。 可以得到輸出:{'DC_2':['55 .200.162.10-55.200.162.13'],'DC_3':['30 .101.102.4'],'DC_1':['23 .201.165.7','27 .101 .178.15-27.101.178.17','50.102.182.2','52.102.182.1','52.102.182.3-52.102.182.5']} –

是的,更改此行:

groups.append("{}-{}".format(group[0], str(group[-1]).split('.')[-1]))

對此:

groups.append("{}-{}".format(group[0], group[-1]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM