如何在特定时间段之间使用python3 argparse读写pcap文件?

时间:2019-02-18 02:53:24

标签: python-3.x datetime argparse

我的具体问题如下。

  1. 如何使用python argparse库搜索和读取特定时间范围内的数据包捕获文件(PCAP)?(例如,从开始时间到结束时间,以及用户指定的两次之间)< / p>

  2. 如何读取特定时间范围内的pcap,然后输出另一个pcap文件?

其他说明:我可以读取pcap文件,但是我不明白如何使用argparse编写pcap文件。请参阅下面的更多细节。

我正在编写python3数据包分析程序,我想在开始时间和停止时间范围之间搜索pcap。我正在使用以下库,我想坚持使用dpkt解析pcaps。

import os
import sys
import socket
import glob
import datetime
import argparse
from binascii import hexlify
import dpkt

我有一些功能可以验证提交的日期和时间。最后,我想添加秒和毫秒,请参见下文

def valid_date_type(arg_date_str):
    """custom argparse *date* type for user dates values given from the command line"""
    try:
        return datetime.datetime.strptime(arg_date_str, "%Y-%m-%d")
    except ValueError:
        msg = "Given Date ({0}) not valid! Expected format, YYYY-MM-DD!".format(arg_date_str)
        raise argparse.ArgumentTypeError(msg)

def valid_datetime_type(arg_datetime_str):
    """custom argparse type for user datetime values given from the command line"""
    try:
        return datetime.datetime.strptime(arg_datetime_str, "%Y-%m-%d %H:%M")
    except ValueError:
        msg = "Given Datetime ({0}) not valid! Expected format, 'YYYY-MM-DD HH:mm'!".format(arg_datetime_str)
        raise argparse.ArgumentTypeError(msg)   

我能够有效地解析数据包,并且除日期和时间参数外,我的所有argparse参数都可以正常工作。以下是一些参数

 parser = argparse.ArgumentParser(description='This is a program to fetch information from pcaps')
    #below is the first argument to read the pcap into fetchit. The type is read binary(rb)
    parser.add_argument("-r", "--read", required=False, type=argparse.FileType('rb'), help="reads a pcapfile")
parser.add_argument("-s", "--session", required=False, action='store_true', help="print the raw session data from a pcap")
parser.add_argument("-dns", "--dns", required=False, action='store_true', help="use the dns decoder")
    #below are my switched for dates and times, these do not work yet. 
    parser.add_argument('-sd', "--startdate", required=False, dest='start_datetime', type=valid_datetime_type, help='start datetime in format "YYYY-MM-DD HH:mm"')
    parser.add_argument('-ed', "--enddate", required=False, dest='end_datetime', type=valid_datetime_type, help='end datetime in format "YYYY-MM-DD HH:mm"')
args = parser.parse_args()

程序读取整个pcap,然后将stdout输出到终端。我已经尝试了百万种方法来读取pcap文件,然后使用argparse写入pcap文件或文本文件。我写out.txt文件的主要方法是使用以下

program.py -r file.pcap -s > out.txt

在此先感谢您的帮助。

J

0 个答案:

没有答案