top of page

Capture Packets Using Python And Pyshark Using Less Than 5 Lines Of Code

Now for something completely different…

I think network professionals should be ‘aware’ of coding.  Not necessarily a programmer, but at least be familiar with what can be done.

So I thought why not combine 2 of my favorite things; python and capturing packets.

All you have to do is install python, where you can get from . Then go to the command prompt and type the following command

pip install pyshark

Use your favorite text editor and create a text file with the extension py and enter the following text.

import pyshark

capture = pyshark.LiveCapture(interface='eth0')



The code is supposed to capture packets for 1 second and stop, but the real purpose of this program is to cause an error so I can get a list of interfaces.  I know its crude, but its effective.

Type python

Find the line that describes your network interface and copy the text above it.

For example, here is the output from my script ,



You need to put \\Device\\NPF_{82C048B7-BF6D-4B92-BDFA-872CFC8F7077}

In my script and make sure you have 2 \\’s

Here is my new code that will capture 100 packets and save it in a test.pcapng

import pyshark

capture = pyshark.LiveCapture(interface='\\Device\\NPF_{82C048B7-BF6D-4B92-BDFA-872CFC8F7077}',output_file='./test.pcapng')

# capture for 5 seconds and stop

# capture.sniff(timeout=5)

#capture 100 packets and stop



Have fun you future coders  😉






Recent Posts

See All


bottom of page