【问题标题】:Get most common ip's from directory full of pcap to csv files从充满 pcap 的目录中获取最常见的 ip 到 csv 文件
【发布时间】:2018-02-28 23:36:23
【问题描述】:

我有一个目录,其中包含从 pcap 转换为 csv 的非常大的 csv 文件。

我正在尝试遍历该目录中的每个 csv 文件并获取最常见的源 IP 地址(第 2 列)。

目前我的输出不正确,因为似乎我已经设法让每个文件在开始之前将其值转储到下一个文件中。每个文件似乎都有相同的 ip,我知道情况并非如此。

ipCounter = collections.Counter()

#iterate through all of the files in the directory, using glob
for filename in glob.glob('/path/to/directory/*'):
    with open(filename) as input_file:
        #skip column titles
        input_file.next()

        for row in csv.reader(input_file, delimiter=','):
            ipCounter[row[2]] += 1

    print 'Source IPs most common in: %s' % filename
    print ipCounter.most_common()

我并不完全是 Python 专家,所以可能有更好的方法来做到这一点,但这是我目前所得到的。

【问题讨论】:

    标签: python python-2.7 csv ip


    【解决方案1】:

    您的方法看起来不错。如果你想做一个每个文件 most_common() 虽然你需要在 for 循环内移动你的计数器。或者有两个计数器,一个为您提供每个文件的总数,第二个为您提供整个文件夹的总数:

    import collections
    import glob
    
    ip_counter_all = collections.Counter()    
    
    for filename in glob.glob('ip*.csv'):
        ip_counter = collections.Counter()
    
        with open(filename) as input_file:
            csv_input = csv.reader(input_file)
            header = next(csv_input)
    
            for row in csv_input:
                ip_counter[row[2]] += 1
    
        ip_counter_all.update(ip_counter)
    
        print '\nSource IPs most common in: {}'.format(filename)
    
        for ip_addr, count in ip_counter.most_common():
            print "  {}  {}".format(ip_addr, count)
    
    print '\nOverall IPs most common:'
    
    for ip_addr, count in ip_counter_all.most_common():
        print "  {}  {}".format(ip_addr, count)
    

    这会给你这样的输出:

    Source IPs most common in: ips.csv
      1.1.1.1  2
      1.2.3.4  1
      1.4.2.3  1
    
    Source IPs most common in: ips2.csv
      1.1.1.1  2
      1.2.3.4  1
      1.4.2.3  1
    
    Overall IPs most common:
      1.1.1.1  4
      1.2.3.4  2
      1.4.2.3  2
    

    您还可以使用较新的 format() 方法来显示您的字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-04
      • 1970-01-01
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 2018-08-26
      • 1970-01-01
      相关资源
      最近更新 更多