使用 Python 读取并打印出 PCAP

Using Python to Read and Print Out a PCAP

这是一项学校作业 Python 相对较新,需要一些帮助。我需要读取一个 PCAP 文件,并将源 IP 和目标 IP 打印到一个新文件中。我不允许使用正则表达式,我不能一次读取整个文件,我必须使用循环、函数(必须接受一个参数和 return 一个值)、拆分、列表和 IP 在IPv4格式。

类 对于这个问题来说是否太复杂了? 编辑:我目前所在的位置如下:下面执行的搜索提取了错误的 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 样本。

如有任何帮助,我们将不胜感激!非常感谢! :)

您阅读的其中一行将包含 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,然后从中提取源和目标。

编辑:

您可以像这样在您的代码中应用它:

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

注意:我假设每个字符串之间将是 \t,如果它不起作用,那么您可能需要添加一些空格或执行类似这样的操作

另请注意:当您使用with 语句打开文件时,您无需尝试关闭该文件,它会自动关闭。您可以查看this article了解更多信息