我正在python3脚本中使用tshark捕获数据包并将输出写入.csv文件。
下面的代码行可以正常工作,并且可以使用“,”作为分隔符将字段正确拆分为.csv文件中的列。
tsharkCall = ["tshark", "-r", pcap, "-T", "fields", "-e", "frame.number", "-e", "_ws.col.Time", "-e", "_ws.col.Source", "-e", "_ws.col.Destination", "-e", "_ws.col.Protocol", "-e", "_ws.col.Length", "-e", "_ws.col.Info", "-E", "header=y", "-E", "separator=,", "-E", "quote=d", "-E", "occurrence=f"]
tsharkOut = open(csv, "wb")
call(tsharkCall, stdout=tsharkOut)
不过,我希望字段(列)标题与保存为.csv时wireshark默认输出的标题匹配
因此,我在互联网上找到了以下内容
tsharkCall = ["tshark", "-r", pcap, "-o", "gui.column.format:", "No.","%m","Time","%t","Source","%s","Destination","%d","Protocol","%p","Length","%L","Info","%i", "-E", "header=y", "-E", "separator=,", "-E", "quote=d", "-E", "occurrence=f"]
但是,当我运行上述修改后的代码时,出现以下错误
tshark: Invalid -o flag "gui.column.format:"
顺便说一句,如果我从终端运行tshark命令,它会创建csv文件,但所有字段都放在单个单元格中,而不是用'分隔,所以我知道tshark在起作用,只是分隔符在没有申请。
tshark -o 'gui.column.format:"No.","%m","Time","%t","Source","%s","Destination","%d","Protocol","%p","Length","%L","Info","%i"' > tst.csv
答案 0 :(得分:0)
您需要从tshark命令中删除-E header=y
并将自己的标头写入文件:
from subprocess import call
tsharkCall = ["tshark", "-r", pcap, "-T", "fields", "-e", "frame.number", "-e", "_ws.col.Time", "-e", "_ws.col.Source", "-e", "_ws.col.Destination", "-e", "_ws.col.Protocol", "-e", "_ws.col.Length", "-e", "_ws.col.Info", "-E", "separator=,", "-E", "quote=d", "-E", "occurrence=f"]
with open(csv, "a") as tsharkOut:
tsharkOut.write("No.,Time,Source,Destination,Protocol,Length,Info\n")
tsharkOut.flush()
call(tsharkCall, stdout=tsharkOut)