2013-11-14 4 views
0

Напишите программу, которая открывает файл tcpdump и переупорядочивает сбрасываемые строки, чтобы пакеты из каждого сеанса группировались вместе. Каждый сеанс выводится в собственный файл с уникальным именем, созданным с IP-адресов и адресов портов этого сеанса.Переупорядочение файла tcpdump сеансом в Python 3

Образец tcpdump.txt:

13:36:21.808234 IP 142.55.112.172.1692 > 142.55.1.9.80: Flags [P.], seq 111310335:111310775, ack 1980466801, win 64427, length 440 
13:36:21.811651 IP 142.55.1.9.80 > 142.55.117.173.3783: Flags [.], seq 2006591246:2006592626, ack 850049956, win 33120, length 1380 
13:36:21.811904 IP 142.55.1.9.80 > 142.55.117.173.3783: Flags [.], seq 1380:2760, ack 1, win 33120, length 1380 
13:36:21.812016 IP 142.55.1.9.80 > 142.55.117.173.3783: Flags [P.], seq 2760:4096, ack 1, win 33120, length 1336 
13:36:21.812278 IP 142.55.1.9.80 > 142.55.117.173.3783: Flags [.], seq 4096:5476, ack 1, win 33120, length 1380 
13:36:21.812413 IP 142.55.117.173.3783 > 142.55.1.9.80: Flags [.], ack 4096, win 65535, length 0 
13:36:21.812538 IP 142.55.1.9.80 > 142.55.117.173.3783: Flags [.], seq 5476:6856, ack 1, win 33120, length 1380 
13:36:21.812876 IP 142.55.117.173.3783 > 142.55.1.9.80: Flags [.], ack 6856, win 65535, length 0 
13:36:21.813234 IP 142.55.1.9.80 > 142.55.117.173.3783: Flags [.], seq 6856:8236, ack 1, win 33120, length 1380 
13:36:21.813358 IP 142.55.1.9.80 > 142.55.117.173.3783: Flags [.], seq 8236:9616, ack 1, win 33120, length 1380 
13:36:21.813396 IP 142.55.117.187.4080 > 142.55.1.9.80: Flags [P.], seq 1883704283:1883704589, ack 2004811294, win 65535, length 306 
13:36:21.813610 IP 142.55.1.9.80 > 142.55.117.173.3783: Flags [P.], seq 9616:10599, ack 1, win 33120, length 983 
13:36:21.813940 IP 142.55.117.173.3783 > 142.55.1.9.80: Flags [.], ack 9616, win 65535, length 0 

Это то, что я до сих пор:

import re 

read_file = open('tcpdump.txt', 'r') 

source_ip = " " 
dest_ip = " " 
source_port = " " 
dest_port = " " 


def four_tuple(line): 
    _search_ = re.compile(r'(\d*\.\d*.\d*.\d*)(\.\d*) > (\d*\.\d*.\d*.\d*)(\.\d*)') 

    source_ip = _search_.search(line).group(1) 
    source_port = _search_.search(line).group(2) 

    dest_ip = _search_.search(line).group(3) 
    dest_port = _search_.search(line).group(4) 

    print('The Source IP and Port are:', source_ip, source_port) 
    print('The Destination IP and Port are:', dest_ip, dest_port) 

for read_lines in read_file: 
    read_file.readline() 
    four_tuple(read_lines) 

Пример вывода до сих пор:

The Source IP and Port are: 142.55.112.172 .1692 
The Destination IP and Port are: 142.55.1.9 .80 
The Source IP and Port are: 142.55.1.9 .80 
The Destination IP and Port are: 142.55.117.173 .3783 
The Source IP and Port are: 142.55.1.9 .80 
The Destination IP and Port are: 142.55.117.173 .3783 
The Source IP and Port are: 142.55.1.9 .80 
The Destination IP and Port are: 142.55.117.173 .3783 
The Source IP and Port are: 142.55.1.9 .80 
The Destination IP and Port are: 142.55.117.173 .3783 
The Source IP and Port are: 142.55.117.187 .4080 
The Destination IP and Port are: 142.55.1.9 .80 

Теперь, как я группа все повторяя IP-адреса в один кластер, чтобы они не повторяли дорогу снова. Так что-то вроде этого было бы идеальным выход:

The Source IP and Port are: 142.55.1.9 .80 
The Destination IP and Port are: 142.55.117.173 .3783 
The Source IP and Port are: 142.55.1.9 .80 
The Destination IP and Port are: 142.55.117.173 .3783 
The Source IP and Port are: 142.55.1.9 .80 
The Destination IP and Port are: 142.55.117.173 .3783 
The Source IP and Port are: 142.55.1.9 .80 
The Destination IP and Port are: 142.55.117.173 .3783 
The Source IP and Port are: 142.55.1.9 .80 
The Destination IP and Port are: 142.55.117.173 .3784 
The Source IP and Port are: 142.55.1.9 .80 
The Destination IP and Port are: 142.55.117.173 .3784 
The Source IP and Port are: 142.55.1.9 .80 
The Destination IP and Port are: 142.55.117.173 .3784 
The Source IP and Port are: 142.55.1.9 .80 
The Destination IP and Port are: 142.55.117.173 .3784 
+0

Это домашнее задание? – RyPeck

ответ

0

Лучший способ питона использовать itertools.groupby. Я переписал ваш пример ниже, не так я может казаться умным, но мы надеемся выделить несколько способов ваш сценарий может быть лучше, или более вещий:

from __future__ import with_statement # Only needed on very old python versions 

import os 
import re 
import sys 
import itertools 


path_to_file = 'tcpdump.txt' 
line_parser = re.compile(r'(\d*\.\d*.\d*.\d*)(\.\d*) > (\d*\.\d*.\d*.\d*)(\.\d*)') 


def parse_line(line): # renamed from four_tuple 
    match = line_parser.search(line) 
    if match: 
     source_ip, source_port, dest_ip, dest_port = match.groups() # Use tuple unpacking to get the variables. 
     return { # A dictionary where each item is given it's own key: value pair. 
      u'source_ip': source_ip, u'source_port': source_port, 
      u'dest_ip': dest_ip, u'dest_port': dest_port, 
      u'line': line, 
     } 
    else: 
     return None # We'll check for a bad match later! 

def main(): 
    parsed_results = [] # We need a place to store our parsed_results from your matcher function. 
    if not os.path.exists(path_to_file): # Only if we can see the file 
     print u'Error, cannot load file: {0}'.format(path_to_file) 
     sys.exit(1) 
    else: 
     with open(path_to_file, 'r') as src_file: # Using the with context, open that file. It will be auto closed when we're done. 
      for src_line in src_file: # for each line in the file 
       results = parse_line(src_line) # run it through your matcher function. 
       if results: 
        parsed_results.append(results) # Place the results somewhere for later grouping and reporting 
       else: 
        print u'[WARNING] Unable to find results in line: "{0}"'.format(repr(src_line)) # Show us the line, without interpreting that line at all. 
    # By now, we're done with the src_file so it's auto-closed because of the with statement 
    if parsed_results: # If we have any results to process 
     # Sort those results by source_ip 
     sort_func = lambda x: x.get(u'source_ip') # We will sort our dictionary items by the source_ip key we extracted earlier in parse_line 
     # First, we have to sort our results so source_ip's are joined together. 
     sorted_results = sorted(parsed_results, key = sort_func) 
     # Now, we group by source_ip using the same sort_func 
     grouped_results = itertools.groupby(sorted_results, key = sort_func) 
     # Here, grouped_results will return a generator which will yield results as we go over it 
     # However, it will only yield results once. You cannot continually iterate over it like a list. 
     for source_ip, results in grouped_results: # The iterator yields the grouped key, then a generator of results on each iterating 
      for result in results: # So, for each result which was previously grouped. 
       print(u'The Source IP and Port are: {0} {1}'.format(result.get(u'source_ip'), result.get(u'source_port'))) 
       print(u'The Destination IP and Port are: {0} {1}'.format(result.get(u'dest_ip'), result.get(u'dest_port'))) 

if __name__ == u'__main__': # This will only execute if this script is run from the command line, and not when it's loaded as a module. 
    main() 

Несколько вещей, которые я сделал по-другому:

  1. Я использовал with statement. Научитесь любить его, это ваш друг здесь.
  2. Определите re.compile вне функции. Таким образом, он компилируется один раз и просто повторно используется каждый раз, в отличие от повторного создания каждого цикла.
  3. На самом деле нет необходимости в read_file.readline(), так как read_file уже iterable. См. Метод next() для this link.
  4. source_ip, source_port и другие могут быть назначены в одной строке с использованием tuple unpacking.
  5. Использование == u 'основной' чек. Это позволяет использовать один и тот же сценарий в качестве модуля и загружать другие скрипты python и как исполняемый скрипт в командной строке. Для получения дополнительной информации см. What does if __name__ == "__main__": do?.

Пожалуйста, не стесняйтесь задавать вопросы, если какой-либо из них кажется продвинутым.

+0

Многие из них кажутся слишком сложными и что-то еще не покрыто классом. Следующим является то, что мой профессор предложил мне сделать для этого вопроса. Мне просто нужно знать, с чего начать, и как поместить каждый список в файл в конце всего этого: – user1819786

+0

Loop file. Извлечь линию. Каждое соединение является уникальным 4-мя туфлями. Извлеките четыре бахромы из каждой строки и закажите/упорядочите ее, чтобы ее можно было использовать как хэш-тег для уникального идентификатора соединения. Используйте хэш-тег в качестве словарного ключа. Поместите строку в список, связанный с ключом хеш-тега. Сделайте это снова для следующей строки в файле. Когда закончите, поместите каждый список в файл. – user1819786

+0

Хорошо, а какая часть этого вы не знаете, как это сделать?Я не написал ответ, чтобы вы могли просто включить его, вместо этого вы должны узнать, что с ним делать. [Возможно, нам стоит взять это в чат] (http://chat.stackoverflow.com/rooms/41230/19967829), если вам нужна помощь в глубине :) – VooDooNOFX

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