2017-09-20 100 views
0

我有一个目录充满了从pcap转换为csv的非常大的csv文件。从pcap目录中获取最常见的ip到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,所以有可能是一个更好的方式来做到这一点,但是这是我到目前为止得到。

回答

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()显示字符串的方法。