在 Python 中使用 Scapy 解析文件
Parsing a file using Scapy in Python
我想使用 Scapy 解析 Python 中的文件,因为我不需要使用 Scapy 的命令提供的所有信息。
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
import sys
from pprint import pprint
with open('myLogFile', 'r+') as f:
sys.stdout = f
print(sniff(filter="udp and port 5060",iface="eth0", prn=lambda x: x.show()))
如果我打开名为 'myLogFile' 的文件,我会看到类似这样的内容:
Screenshot of the result
我的愿望是只取回 IP "src" 和 "dest" 的 IP 标题,以及每辆电车的负载,但我不知道该怎么做,我是 Python.
有一个简单的解决方案,如果 f
是您要写入的文件对象:
sniff(filter="udp and port 5060", iface="eth0",
prn=lambda x: f.write(x.sprintf("%IP.src% %IP.dst% %UDP.payload%\n")))
这假定您不想格式化负载。如果它包含二进制数据,您可能需要使用 Python 的 repr()
来转义它:
sniff(filter="udp and port 5060", iface="eth0",
prn=lambda x: f.write(x.sprintf("%IP.src% %IP.dst% ") + repr(str(x[UDP].payload)) + '\n'))
我想使用 Scapy 解析 Python 中的文件,因为我不需要使用 Scapy 的命令提供的所有信息。
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
import sys
from pprint import pprint
with open('myLogFile', 'r+') as f:
sys.stdout = f
print(sniff(filter="udp and port 5060",iface="eth0", prn=lambda x: x.show()))
如果我打开名为 'myLogFile' 的文件,我会看到类似这样的内容:
Screenshot of the result
我的愿望是只取回 IP "src" 和 "dest" 的 IP 标题,以及每辆电车的负载,但我不知道该怎么做,我是 Python.
有一个简单的解决方案,如果 f
是您要写入的文件对象:
sniff(filter="udp and port 5060", iface="eth0",
prn=lambda x: f.write(x.sprintf("%IP.src% %IP.dst% %UDP.payload%\n")))
这假定您不想格式化负载。如果它包含二进制数据,您可能需要使用 Python 的 repr()
来转义它:
sniff(filter="udp and port 5060", iface="eth0",
prn=lambda x: f.write(x.sprintf("%IP.src% %IP.dst% ") + repr(str(x[UDP].payload)) + '\n'))