Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Capture traffic for a particular VM on an ESXi host, using pktcap-uw. Assists with finding the PORT-ID and most common interesting capture points.
#!/bin/sh
#Manage packet capture of a particular VM running on this ESXi host
#How to use, on an ESXi host:
# Download the script to /tmp and make it executable.
# $ chmod +x capture-vm-traffic.sh
# $ ./capture-vm-traffic.sh start your-vm-name
# Do stuff you want captured, then
# $ ./capture-vm-traffic.sh stop
# You get three files containing the in, out, and drops for the VM's vnic
#Tested on ESXi 6.5.0 build 5224529
#Jeff Green, 2017
if [ "$1" == "start" ]; then
echo "Obtaining first hit on world port for given VM name $2"
worldId=$(esxcli network vm list | grep $2 | head -n 1 | cut -d ' ' -f 3)
echo "Got world ID: $worldId"
portId=$(esxcli network vm port list -w $worldId | head -n 1 | cut -d ':' -f 2 | cut -d ' ' -f 2)
echo "Got port ID: $portId"
read -p "Press enter to start capture, CTRL-C to cancel..."
echo "Starting capture PortInput"
pktcap-uw --switchport $portId --capture PortInput -o cap_$2_in.pcap > /dev/null 2>&1 &
echo "Starting catpure PortOutput"
pktcap-uw --switchport $portId --capture PortOutput -o cap_$2_out.pcap > /dev/null 2>&1 &
echo "Starting capture Drop"
pktcap-uw --switchport $portId --capture Drop -o cap_$2_drop.pcap > /dev/null 2>&1 &
echo "Captures probably started. Saving as cap_$2_[in|out|drop].pcap in $(pwd)"
ps | grep pktcap-uw
elif [ "$1" == "stop" ]; then
echo "Stoppin' ALL pktcap-uw instances!"
pkill pktcap-uw
sleep 2
echo "Remaining instances (should be empty):"
ps | grep pktcap-uw
echo "Done"
else
echo "Huh? Usage:"
echo " start <vm name> -- Start in/out/drop capture for first matching port"
echo " stop -- Stop all pktcap-uw instances"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment