Windows Powershell script for automating packet captures when an alarm event shows in the logs

This post is for monitoring the event logs through a power shell script and then execute a wireshark from command line to start a packet capture for the desired time.  Below is a template for such a script which can be modified according to each situation.

Pre-requirements:

  • Installed wireshark on your server
  • Enabled powershell to execute scripts (Windows settings)

Steps:

1. Identify the network interface as wireshark sees them 

2. Set the desired path for storing the pcaps

3. Choose for how long or how big will the captures be, this would depend on the limitations of the server for space and network traffic. Wireshark offers several conditions for autostop of a capture. For example, some available stop conditions are:
-c <packet count>        stop after n packets (def: infinite)
-a <autostop cond.> …, –autostop <autostop cond.> …
                           duration:NUM – stop after NUM seconds
                           filesize:NUM – stop this file after NUM KB
                           files:NUM – stop after NUM files
                           packets:NUM – stop after NUM packets

4. Create and execute a scheduled task that runs the script periodically. You can choose how frequent to check depending on how long the network events usually are and for how long will the capture be. (Be cautious of not executing more than one capture at a time)

    The code snippet below checks for log messages from the source called “VPNagent” only, which include the words DOWN,Error,IPPKT_SHUTDOWN and WSAETIMEOUT. More matches could potentially be included inside that if clause. Then it outputs on the shell that it has found matching events and executes the wireshark command. 

    The wireshark command will start a capture immediately(-k) on interface 4 (-i 4) , stop after a duration of 30 seconds (-a duration:30) and store the capture as “C:\test.pcap” (-w ).

    if( Get-EventLog -source "VPNagent" -Logname "Application" -After (Get-Date).addMinutes(-1) | where {($_.Message -Match "DOWN") -or ($_.EntryType -Match "Error") -or ($_.Message -Match "IPPKT_SHUTDOWN") -or ($_.Message -Match "WSAETIMEOUT") }){
    	Write-Host "Found events to TroubleShoot..., triggering actions";
    	#Change the device id for the -i flag below accordingly
    	'C:\Program Files\Wireshark\Wireshark.exe' -i 4 -k -a duration:30 -w C:\test.pcap
    }

    Leave a comment