使用Python读取并打印出PCAP。

问题描述 投票:2回答:1

这是一个学校作业,我是Python新手,需要一些帮助。我需要读取一个PCAP文件,并将源和目标IP打印到一个新文件中。我不允许使用regex,我不能一次读完整个文件,我必须使用循环、函数(必须接受一个参数并返回一个值)、分割和列表,而且IP是IPv4格式。

类是否太复杂了,这个问题吗? EDIT:我目前的情况如下。下面进行的搜索拉出了错误的IP。建议我按查找号时间来源目的协议进行搜索。

然后从它下面的一行打印IP。我正在研究如何根据XXX.XXX.XXX格式进行过滤,会告诉你结果如何:)

def pcapreader():

#open the file and print each line using readlines to a variable
#must replace file path with your present file location


    with open (r"filepath", "r") as f:
        f1=f.readlines()
        for x in f1:
            if "Internet Protocol Version 4, Src:" in x:
                ips = x.split("Src: ")[1].split(",")
                src = ips[0]
                dst = ips[1].split("Dst: ")[1]
                print("Src: {}\nDst:{}".format(src, dst))

    f.close()

def main ():

        pcapreader()


main()

我已经附上了我需要阅读的PCAP的样本。enter image description here

任何帮助将被感激! 非常感谢! :) :)

python-3.x pcap
1个回答
2
投票

读取的行中有一行将包含 Internet Protocol Version 4, Src: 然后是源,后面是目标。

所以,对于这一行,你可以做如下操作。

>>> ips = "Internet Protocol Version 4, Src: 192.168.1.180, Dst: 239.255.255.250"
>>> ips = ip.split("Src: ")[1].split(",")
>>> ips
['192.168.1.180', ' Dst: 239.255.255.250']
>>> src = ips[0]
>>> dst = ips[1].split("Dst: ")[1]
>>> src
'192.168.1.180'
>>> dst
'239.255.255.250'

这一行的名字是 ips 的例子中,然后从中提取出源和目的。

EDIT:

你可以把它应用在你的代码中,像这样。

with open (r"filepath", "r") as f:
    f1=f.readlines()
    for x in f1:
      if "Internet Protocol Version 4, Src:" in x:
        ips = x.split("Src: ")[1].split(",")
        src = ips[0]
        dst = ips[1].split("Dst: ")[1]
        print("Src: {}\nDst:{}".format(src, dst))
        break

希望能帮到你。

补充:在最后的编辑中,如果你想从下面的行中得到数据,那么你可以用 Time Source ... 你可以这样做。

with open (r"filepath", "r") as f:
    f1=f.readlines()
    flag = False
    for x in f1:
      if "No.\tTime\tSource" in x:
        flag = True
        continue

      if flag:# This will be executed just at the line after No.\tTime\tSource...
        src = x.split("\t")[3]
        dst = x.split("\t")[4]
        print("Src: {}\nDst: {}".format(src, dst))
        flag = False

注意: 我假设每个字符串之间都有一个空格,如果它不工作,那么你也许要加一些空格或者做一些类似的事情

另一个注意:当你使用 with 语句来打开文件,你不需要尝试关闭该文件,它将自动关闭。你可以看到 本文 更多信息

© www.soinside.com 2019 - 2024. All rights reserved.