diff --git a/scapy/utils.py b/scapy/utils.py index c3febf59e2bb97d9f1d61172b8e900cab20c17c8..a5b38fa9eba80087a45b64c0d745b7431f1734b0 100644 --- a/scapy/utils.py +++ b/scapy/utils.py @@ -535,9 +535,18 @@ def corrupt_bits(s, p=0.01, n=None): @conf.commands.register def wrpcap(filename, pkt, *args, **kargs): """Write a list of packets to a pcap file + +filename: the name of the file to write packets to, or an open, + writable file-like object. The file descriptor will be + closed at the end of the call, so do not use an object you + do not want to close (e.g., running wrpcap(sys.stdout, []) + in interactive mode will crash Scapy). gz: set to 1 to save a gzipped capture linktype: force linktype value -endianness: "<" or ">", force endianness""" +endianness: "<" or ">", force endianness +sync: do not bufferize writes to the capture file + + """ with PcapWriter(filename, *args, **kargs) as fdesc: fdesc.write(pkt) @@ -829,27 +838,36 @@ class RawPcapWriter: """A stream PCAP writer with more control than wrpcap()""" def __init__(self, filename, linktype=None, gz=False, endianness="", append=False, sync=False): """ - linktype: force linktype to a given value. If None, linktype is taken - from the first writter packet - gz: compress the capture on the fly - endianness: force an endianness (little:"<", big:">"). Default is native - append: append packets to the capture file instead of truncating it - sync: do not bufferize writes to the capture file +filename: the name of the file to write packets to, or an open, + writable file-like object. +linktype: force linktype to a given value. If None, linktype is taken + from the first writter packet +gz: compress the capture on the fly +endianness: force an endianness (little:"<", big:">"). Default is native +append: append packets to the capture file instead of truncating it +sync: do not bufferize writes to the capture file + """ self.linktype = linktype self.header_present = 0 - self.append=append + self.append = append self.gz = gz self.endian = endianness - self.filename=filename - self.sync=sync + self.sync = sync bufsz=4096 if sync: - bufsz=0 + bufsz = 0 + + if isinstance(filename, basestring): + self.filename = filename + self.f = [open,gzip.open][gz](filename,append and "ab" or "wb", gz and 9 or bufsz) + else: + self.f = filename + self.filename = (filename.name + if hasattr(filename, "name") else + "No name") - self.f = [open,gzip.open][gz](filename,append and "ab" or "wb", gz and 9 or bufsz) - def fileno(self): return self.f.fileno() @@ -908,7 +926,7 @@ class RawPcapWriter: usec = int(round((t-it)*1000000)) self.f.write(struct.pack(self.endian+"IIII", sec, usec, caplen, wirelen)) self.f.write(packet) - if self.gz and self.sync: + if self.sync: self.f.flush() def flush(self): @@ -925,6 +943,7 @@ class RawPcapWriter: class PcapWriter(RawPcapWriter): + """A stream PCAP writer with more control than wrpcap()""" def _write_header(self, pkt): if self.linktype == None: try: