Skip to content

Instantly share code, notes, and snippets.

@gnilchee
Created June 30, 2025 04:34
Show Gist options
  • Save gnilchee/e9e317da263c17ad3d642dd9b6754b1b to your computer and use it in GitHub Desktop.
Save gnilchee/e9e317da263c17ad3d642dd9b6754b1b to your computer and use it in GitHub Desktop.
DNS capture script - includes auto rotation
#!/bin/bash
# Configuration
INTERFACE="eth0" # Your network interface
DNS_SERVER_IP="8.8.8.8" # The IP of your specific DNS server
LOG_DIR="/var/log/dns_tcpdump" # Directory to store the log files
LOG_FILE_PREFIX="dns_capture" # Prefix for the log file names
MAX_FILE_SIZE_MB=10 # Maximum size of each PCAP file in MB
NUM_ROTATING_FILES=5 # Number of rotated files to keep
# --- DO NOT EDIT BELOW THIS LINE ---
# Ensure the log directory exists
mkdir -p "$LOG_DIR" || { echo "Error: Could not create log directory $LOG_DIR"; exit 1; }
# Construct the tcpdump command with rotation options
# -C <size>: Before writing a raw packet to a savefile, check whether the file is
# currently larger than 'size' (in millions of bytes) and, if so,
# close the current savefile and open a new one.
# -W <count>: Used in conjunction with -C, this will limit the number of files
# created to the specified number, and begin overwriting files from
# the beginning, thus creating a 'rotating' buffer.
TCPDUMP_CMD="sudo tcpdump -i $INTERFACE -n -vv udp port 53 and host $DNS_SERVER_IP -C $MAX_FILE_SIZE_MB -W $NUM_ROTATING_FILES -w $LOG_DIR/$LOG_FILE_PREFIX"
echo "Starting tcpdump capture with logging and rotation..."
echo "Interface: $INTERFACE"
echo "DNS Server: $DNS_SERVER_IP"
echo "Log Directory: $LOG_DIR"
echo "Max File Size: ${MAX_FILE_SIZE_MB}MB"
echo "Number of Rotating Files: $NUM_ROTATING_FILES"
echo "Press Ctrl+C to stop."
# Execute tcpdump
# The `exec` command replaces the current shell process with the tcpdump process.
# This is generally a good practice for long-running processes in scripts,
# as it avoids creating an extra process.
exec $TCPDUMP_CMD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment