开发者

opening a pcap file in python

I'm trying to open a .pcap file in python. can anyone help with this? each time I try this, it gives an error mess开发者_StackOverflow中文版age that "IOError: [Errno 2] No such file or directory: 'test.pcap'"

import dpkt
f = open('test.pcap')
pcap = dpkt.pcap.Reader(f)


Try giving open() the correct path to test.pcap:

f = open(r'C:\Users\hollandspur\Documents\test.pcap')

or some such...


As Tim pointed out above you probably need to use the entire file path because you're not in the same directory. If you're running from the interpreter you can check your path using the following:

import os
os.getcwd()

If you're not in the same directory as where you're file is stored then you need the full file path. You can type the whole thing in, or with a little more work you can accept relative file paths.

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)

This would allow you to give a path such as "../test.pcap" which would go up one directory and look for the file. This is especially useful if you are running this script from the command line or your file is in a different directory that is close to the current directory.

You may also want to look into functions such as os.path.isfile(fullPath) that would let you check if the file exists


You should read as a binary file. See the 'rb' parameter which indicates to read this as binary file import dpkt f = open('test.pcap','rb') pcap = dpkt.pcap.Reader(f)


I'm trying to open a .pcap file in python. can anyone help with this? each time I try this, it gives an error message that IOError: [Errno 2] No such file or directory: 'test.pcap'

Try this code: try this code to overcome the above 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜