There was a question on the Wireshark Q&A Site. A user wanted to apply a filter to only show the last few packets of all TCP flows. This can be done manually in Wireshark quite easily but the user had hundreds of flows and was looking for an automatic way to do this.
Here is a quick post with code that demonstrates how you can automate this and other custom analysis using Unsniff Network Analyzer.
Unsniff exposes an object model to scriptland. This means that flows (a.k.a streams), packets, user objects, PDUs are all top level objects. All you have to do is to grab the flows collection, then for each flow save the last 6 packets. Here is the script.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
' ' lastn - Dump last 5 packets of every stream into a separate PCAP file Set Sout = WScript.StdOut If WScript.Arguments.Count <> 2 Then Sout.WriteLine "Usage: cscript last5.vbs input-pcap output-pcap " WScript.Quit End If InputTCPD = WScript.Arguments.Item(0) OutputTCPD = WScript.Arguments.Item(1) Dim fso Set fso = CreateObject("Scripting.FileSystemObject") ' Import from input libpcap to USNF format Set UnsniffDB = CreateObject("Unsniff.Database") UnsniffDB.New("temp_cap.usnf" ) UnsniffDB.Import "libpcap", InputTCPD Sout.WriteLine "Imported tcpdump file " & InputTCPD ' New USNF - to be exported to output file Set UnsniffDBOut = CreateObject("Unsniff.Database") UnsniffDBOut.New("temp_cap2.usnf" ) Sout.WriteLine "Opened usnf output file " Dim STIndex Set STIndex = UnsniffDB.StreamIndex For Each ST In STIndex With ST Set Pkts = ST.Packets If Pkts.Count > 5 Then FromIdx = Pkts.Count-6 ToIdx = Pkts.Count-1 Else FromIdx = 0 ToIdx = Pkts.Count-1 End If Sout.WriteLine "Exporting packets " & FromIdx & " to " & ToIdx & " in stream " & ST.ID For Idx = FromIdx To ToIdx UnsniffDBOut.AddPacket(Pkts.Item(Idx)) Next End With Next UnsniffDB.Close() UnsniffDBOut.Export "libpcap",OutputTCPD UnsniffDBOut.Close() fso.DeleteFile "temp_cap.usnf" fso.DeleteFile "temp_cap2.usnf" |
The main part of the code is
- Get the StreamIndex
- Iterate over all streams; for each stream; grab the last 5 packets
- Add those packets to the new output file
1 2 3 |
Set STIndex = UnsniffDB.StreamIndex For Each ST In STIndex Set Pkts = ST.Packets |
To run this script ;
- Download and Install Unsniff Network Analyzer
- Copy the above code into a file say lastn.vbs
Run as
1 |
cscript lastn.vbs inputfile.pcap outputfile.pcap |
What you will end up with is a new capture file containing only the last 5 segments of each flow. See pictures below.
The automation capabilities of Unsniff can save precious time. Please visit the Unsniff Scripting Guide for more.