2014-09-10 2 views
0

Учитывая файл журнала, который имеет отметку времени ф и другую информацию, как показано ниже:Python скрипта для создания отчета пакета уронить

22:30 1.1.1.2 buffer overflow 
22:30 1.1.1.2 drops 10 packets 
22:30 1.1.1.3 drops 15 packets 
22:35 1.1.1.2 drops 20 packets 

Я хочу, чтобы разобрать журнал и вывод:

1.1.1.2 dropped a total of 30 packets 
1.1.1.3 drooped a total of 15 packets 

I начинал как:

f = open('log.txt', 'r') 
for line in f: 
    if 'drops' in line: 
    output = line.split()[1:] 
    print output[1], output[3] 

Это даст мне:

1.1.1.2 10 
1.1.1.3 15 
1.1.1.2 20 

Я не уверен, как chk для того же ip, а затем добавьте пакеты. Может кто-нибудь помочь? Thx

ответ

1

Вы можете использовать defaultdict для этой цели

from collections import defaultdict 

d=defaultdict(int,{}) 
f = open('a.txt', 'r') 
for line in f: 
    if 'drops' in line: 
     data=line.split() 
     d[data[1]]=d.setdefault(data[1], 0)+ int(data[3]) 
f.close() 
print d 

defaultdict(<type 'int'>, {'1.1.1.2': 30, '1.1.1.3': 15}) 

если defaultdict является overkilling мы можем просто использовать ДИКТ

d={} 
f = open('a.txt', 'r') 
for line in f: 
    if 'drops' in line: 
     data=line.split() 
     d[data[1]]=d.setdefault(data[1], 0)+ int(data[3]) 
print d 
1

собрать все IP-адреса, как ключ Dict и добавить packet_lost Num в качестве значения

>>> ip_dict = {} 
>>> with open('file.txt') as f: 
...  for line in f: 
...   if 'drops' in line: 
...    output  = line.split()[1:] 
...    ip   = output[0] 
...    packet_lost = output[2] 
...    if not ip_dict.get(ip,{}): 
...     ip_dict[ip] = 0 
...    ip_dict[ip] += int(packet_lost) 
... 
>>> 
>>> ip_dict 
{'1.1.1.2': 30, '1.1.1.3': 15} 

Затем вы можете interate и формат вывода

>>> for ip, total in ip_dict.iteritems(): 
...  print '%s dropped a total of %i packets' % (ip,total) 
... 
1.1.1.2 dropped a total of 30 packets 
1.1.1.3 dropped a total of 15 packets 
2
with open('log.txt', 'r') as f: 
    drops = {} 
    for line in f: 
     if 'drops' in line: 
      time, ip, fn, n, packets = line.split() 
      drops[ip] = drops.get(ip, 0) + int(n) 
for ip, count in drops.items(): 
    print ip, count 

Это производит вывод:

1.1.1.2 30 
1.1.1.3 15 

Два пункта, чтобы отметить в этом коде:

  • Используется python's with, чтобы вы могли быть уверены, что файл закрыт, когда он больше не нужен.

  • Данные распаковывается в переменные с значимыми именами:

    time, ip, fn, n, packets = line.split() 
    

    Это делает линию, которая следует более читаемым.

Смежные вопросы