【问题标题】:Using Python to Read and Print Out a PCAP使用 Python 读取和打印 PCAP
【发布时间】:2020-08-28 01:50:58
【问题描述】:

这是学校作业 对 Python 比较陌生,需要一些帮助。我需要读取一个 PCAP 文件,并将源 IP 和目标 IP 打印到一个新文件中。我不允许使用正则表达式,我不能一次读取整个文件,而且我必须使用循环、函数(必须接受一个参数并返回一个值)、拆分,并且列表和 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 样本。

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

【问题讨论】:

  • 更新:试图通过对打印为字符串的每一行使用过滤器选项来思考我的方式,但不确定如何
  • 附件中是否包含文件行?

标签: python-3.x pcap


【解决方案1】:

您阅读的其中一行将包含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了解更多信息

【讨论】:

  • 谢谢 Kasper,我会试一试!那会在第一个函数中吗?
  • 不客气。是的,您应该检查字符串Internet Protocol Version 4 是否在x 变量中。
  • 非常感谢您的编辑,在代码中看到它有很大帮助!我试试看:)
  • 效果很好!我只能检索 src 和 dst IP 作为输出,非常感谢!
  • 尝试在 if 语句中打印 x 以查看该行的确切外观。如果您确定 16 个空格,则可以将它们用作分隔符而不是 \t
猜你喜欢
  • 2017-06-20
  • 2012-04-22
  • 2013-05-27
  • 2012-09-16
  • 1970-01-01
  • 2016-11-22
  • 1970-01-01
  • 1970-01-01
  • 2019-09-15
相关资源
最近更新 更多