Search code examples
pythonpipestdoutpcap

Python: piping pcap file to stdout gives error


I am trying to pipe the output of xz to a custom python script:

xz -cd file.pcap.xz | myscripy.py

However, I get an error when the script attempts to run this line:

  #!/usr/bin/env python2.7
from __future__ import print_function

import pcap
import io
STDIN_ALIAS = '/proc/self/fd/0' 

pcap.pcap(io.open(STDIN_ALIAS, 'r'))

and received an error

    pcap.pcap(io.open(STDIN_ALIAS, 'r'))
  File "pcap.pyx", line 196, in pcap.pcap.__init__
TypeError: expected string or Unicode object, _io.TextIOWrapper found

I am on Ubuntu 18.04 and running under python 2.7.


Solution

  • You can't use Python to pass in packets from a file to pcap.pcap(). The pypcap library you are using is a thin wrapper around the pcap_open_offline() and pcap_create() C functions, and offers no facilities for passing in a Python file object. This wrapper only accepts a filename or a network interface name, nothing else.

    The pcap_open_offline() function does accept - as an alias for stdin, so just pass that in directly:

    import pcap
    
    sniffer = pcap.pcap('-')