简体   繁体   English

CSV读写-IP匹配IP范围

[英]CSV read & write - IP matching IP Range

I've got an issue but don't really have sufficient Python knowledge to solve it. 我遇到了一个问题,但实际上并没有足够的Python知识来解决它。 I found some similar cases so for someone who is really good at Python this is probably a really small task to solve, if you would like! 我发现了一些类似的案例,所以对于一个真正精通Python的人来说,如果您愿意的话,这可能是一个非常小的任务!


Problem: Write a list of failed IP's within a monitored range from two input sources 问题:在两个输入源的监视范围内写入失败IP的列表

  1. I've got a CSV file with two columns, "FailedIPs.csv": 我有一个包含两列“ FailedIPs.csv”的CSV文件:

     State, FailedIP, 1, 178.203.178.159, 
  2. Then I've got another file with ISP name and CIDR, "IPranges.csv": 然后,我得到了另一个带有ISP名称和CIDR的文件“ IPranges.csv”:

     ISPname, IPrange, Vodafone, 88.128.64.0/18, 
  3. I want to produce a CSV which contains all the failed IP addresses that are in one of the supplied ranges: 我想生成一个CSV,其中包含所提供范围之一中的所有失败IP地址:

     State, FailedIP, ISPname, IPrange, 1, 178.203.178.159, Vodafone, 168.00.64.0/32, 

I found some similar questions here on StackOverflow: 我在StackOverflow上发现了一些类似的问题:

Looking forward to any Python "pro" (from my point of view) that would like to help! 期待任何对我有帮助的Python“专家”(以我的观点)! :) :)

#!/usr/bin/env python2
import csv
from IPy import IP

def get_IP_ranges(filename):
    with open(filename, 'rb') as csv_file:
        csv_reader = csv.reader(csv_file)
        next(csv_reader) # skip header
        for ISP, IP_range in csv_reader:
            yield IP(IP_range, make_net=True), ISP

def get_failed_IPs(filename):
    with open(filename, 'rb') as csv_file:
        csv_reader = csv.reader(csv_file)
        next(csv_reader) # skip header
        for state, failed_IP in csv_reader:
            yield state, IP(failed_IP)

IP_ranges = tuple(get_IP_ranges('IPranges.csv'))
with open('join.csv', 'wb') as join_csvfile:
    join_writer = csv.writer(join_csvfile)
    join_writer.writerow(('State', 'FailedIP', 'ISPname', 'IPrange'))
    for state, failed_IP in get_failed_IPs('FailedIPs.csv'):
        for IP_range, ISP in IP_ranges:
            if failed_IP in IP_range:
                break
        else:
            continue
        join_writer.writerow((state, failed_IP, ISP, IP_range))

It uses the IPy library. 它使用IPy库。

Below is an example of how you might load the files with the csv module, and use a function to test whether the IP address from the first file falls within an IP range for the other. 下面是一个示例,说明如何使用csv模块加载文件,并使用函数测试第一个文件的IP地址是否在另一个文件的IP范围内。 I'm not familiar with using IP addresses, but as suggested above, the ipaddress module would probably be useful here. 我对使用IP地址不熟悉,但是如上文所述,在这里ipaddress模块可能会有用。

import csv

#Modify this function to check if an IP address falls within a range
def ismatch(ipadress, iprange):
    return ipadress == iprange

#Load CSVs
failed = csv.DictReader(open('File1 CSV IPfailed.csv'))
ranges = csv.DictReader(open('File2 CSV IPrange.csv'))
#list for ranges, since will iterate multiple times
rangelist = [row for row in ranges]

#Add cases where FailedIP entry == IPrange entry
matches = []
for ii in failed:
    for jj in rangelist:
        if ismatch(ii[' FailedIP'], jj[' IPrange']):
            ii.update(jj)                       #merge jj dict entries into ii
            matches.append(ii)                  #add to matches

#Output
fieldnames = ranges.fieldnames + failed.fieldnames      #list of all field names
with open('IPmatches.csv', 'w') as f_out:
    writer = csv.DictWriter(f_out, fieldnames)
    writer.writeheader()
    writer.writerows(matches)

One thing to note is that the fieldnames begin with spaces, since there is a space between each field in the header of your CSV files. 要注意的一件事是,字段名以空格开头,因为CSV文件标题中的每个字段之间都有一个空格。 If your fieldnames are within quotes in the header of your CSV files, then the DictReader won't append those spaces in front. 如果您的字段名在CSV文件标题的引号中,则DictReader不会在前面加上这些空格。

As this script iterates through the IP ranges for each failed IP address, it may not scale to your problem. 当此脚本遍历每个失败IP地址的IP范围时,它可能无法解决您的问题。 Like UpAndAdam mentioned above, simplifying the components of the problem you're trying to solve (matching IPs, using csv ), would be helpful for offering more detailed advice. 就像上面提到的UpAndAdam一样,简化您要解决的问题的组成部分(使用csv匹配IP),将有助于提供更详细的建议。

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

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