我试图在python中打开.pcap文件。有人能帮忙吗?每个我尝试这一次,它提供了一个错误消息"IOError: [Errno 2] No such file or directory: 'test.pcap'"
在python中打开pcap文件
import dpkt
f = open('test.pcap')
pcap = dpkt.pcap.Reader(f)
我试图在python中打开.pcap文件。有人能帮忙吗?每个我尝试这一次,它提供了一个错误消息"IOError: [Errno 2] No such file or directory: 'test.pcap'"
在python中打开pcap文件
import dpkt
f = open('test.pcap')
pcap = dpkt.pcap.Reader(f)
先给open()
的正确路径test.pcap
:
f = open(r'C:\Users\hollandspur\Documents\test.pcap')
或一些这样...
蒂姆指出您可能需要使用整个文件路径,因为您不在同一个目录中。如果你从解释运行,就可以使用以下命令来检查您的路径:
import os
os.getcwd()
如果在同一个目录中,你是文件存储,那么你需要完整的文件路径不是。您可以键入整个内容,或者使用更多的工作来接受相关文件路径。
import os
relativePath = 'test.pcap' # Relative directory something like '../test.pcap'
fullPath = os.path.join(os.getcwd(),relativePath) # Produces something like '/home/hallandspur/Documents/test.pcap'
f = open(fullPath)
这将允许你给这会转到上一级目录下,寻找文件的路径,例如"../test.pcap"
。如果您从命令行运行此脚本,或者您的文件位于与当前目录接近的其他目录中,这一点尤其有用。
您可能还需要寻找到的功能,如os.path.isfile(fullPath)
,将让您检查文件是否存在
我想在python打开.pcap文件。有人能帮忙吗?每个我尝试这一次,它提供了一个错误消息
IOError: [Errno 2] No such file or directory: 'test.pcap'
试试这个代码:试试这个代码,以克服上述的ioerror
import dpkt,sys,os
"""
This program is open a pcap file and
count the number of packets present in it.
it also count the number of ip packet, tcp packets and udp packets.
......from irengbam tilokchan singh.
"""
counter=0
ipcounter=0
tcpcounter=0
udpcounter=0
filename=raw_input("Enter the pcap trace file:")
if os.path.isfile(filename):
print "Present: ",filename
trace=filename
else:
print "Absent: ",filename
sys.stderr.write("Cannot open file for reading\n")
sys.exit(-1)
for ts,pkt in dpkt.pcap.Reader(open(filen,'r')):
counter+=1
eth=dpkt.ethernet.Ethernet(pkt)
if eth.type!=dpkt.ethernet.ETH_TYPE_IP:
continue
ip=eth.data
ipcounter+=1
if ip.p==dpkt.ip.IP_PROTO_TCP: #ip.p == 6:
tcpcounter+=1
#tcp_analysis(ts,ip)
if ip.p==dpkt.ip.IP_PROTO_UDP: #ip.p==17:
udpcounter+=1
print "Total number of packets in the pcap file :", counter
print "Total number of ip packets :", ipcounter
print "Total number of tcp packets :", tcpcounter
print "Total number of udp packets :", udpcounter
你应该读作二进制文件。请参阅“rb”参数,该参数表示将其读取为二进制文件 import dpkt f = open('test.pcap','rb') pcap = dpkt.pcap.Reader(f)
错误不清楚?你的代码没有看到你的'test.pcap'文件 – SilentGhost 2010-07-02 10:11:11