Thursday, May 10, 2012

Use pcapy and impacket to interact with libpcap in Python

I need to read and analyze some TCP packets in Windows Python 2.7. After some google search, I decided to give pcapy and impacket a shot because they are easier to use as shown in http://snipplr.com/view/3579/.

The first step is to install them on my Windows box. I tried easy_install and it stopped due to an error of "not being able to find pcap.h". To fix the problem, I downloaded the latest winpacp developer's pack from http://www.winpcap.org/devel.htm. After unzipping the content to the same directory that cl.exe looks for, everything went well. There is no problem with installing impacket using easy_install.

The second step is to write a simple script to read some TCP packets from one network interface. Here is my readLivePacket.py:

from pcapy import findalldevs,open_live
from impacket import ImpactDecoder, ImpactPacket


devices = findalldevs();
pc = open_live(devices[1], 2048, False, 1000)
pc.setfilter('tcp')

  
def processPacket(hdr, data):
    decoder = ImpactDecoder.EthDecoder()
    packet=decoder.decode(data)
    ippacket=packet.child()
    tcppacket=packet.child()
    print tcppacket
  
packet_limit = -1
pc.loop(packet_limit, processPacket)

Once the script starts, it captured and printed out all TCP packets as shown here.

I also want my script to read and analyze packets from pcap file.  Here is my readPacketFile.py:


from pcapy import findalldevs,open_offline
from impacket import ImpactDecoder, ImpactPacket


fileName="c:\\temp\\rsa\\test.pcap"


pc = open_offline(fileName)
pc.setfilter('tcp')


  
def processPacket(hdr, data):
    decoder = ImpactDecoder.EthDecoder()
    packet=decoder.decode(data)
    ippacket=packet.child()
    tcppacket=packet.child()
    
    print tcppacket
  
packet_limit = -1
pc.loop(packet_limit, processPacket)


pcapy and impacket make the job of analyzing network traffic easy for Python.

1 comment:

  1. I'm getting the output like "Aborted" when I run the readLivePacket.py script in kali linux. Could you please help me to resolve this?
    Thanks in advance...
    Kali

    ReplyDelete