Time-based Packet Capture with tcpdump

From Jwiki
Revision as of 10:41, 27 August 2025 by Gyurci08 (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


Creating a Continuous Packet Capture without a Script

A common challenge with `tcpdump` is that its built-in file rotation (`-G`) can be unreliable; the process may exit or fail due to permission errors. This occurs because, by default, `tcpdump` drops its root privileges after starting, which interferes with its ability to manage files in protected directories.

You can solve this without a wrapper script by using the `-Z` option to specify which user `tcpdump` should run as after it has initialized the capture.

The Command

This one-liner command runs `tcpdump` with time-based rotation and explicitly tells it to use the `root` user for file operations. This ensures it has the necessary permissions to continuously overwrite the capture file every 30 minutes.

tcpdump -i any -w /tmp/capture.pcap -G 1800 -W 1 -Z root 'host hostname.asd.local and port 12345'

Parameter Breakdown

  • -i any: Listen on all network interfaces.
  • -w /tmp/capture.pcap: Writes the raw packet output to a file.
  • -G 1800: Sets the rotation interval. It triggers a file rotation every 1800 seconds (30 minutes).
  • -W 1: Limits the number of capture files to one, ensuring the same file is overwritten.
  • -Z root: This is the crucial flag. It tells `tcpdump` to change its user to `root` after opening the capture device. Since it's running as root, it will have no problem writing or overwriting the file in `/tmp/` during rotation.
  • 'host ... and port ...': The filter expression to capture only the traffic you need.

Why This Method Works

This approach directly addresses the privilege-dropping issue. By forcing `tcpdump` to operate as the `root` user with `-Z root`, you ensure that when the 30-minute rotation occurs, the process still has sufficient permissions to manage the capture file. This prevents both the "Permission denied" error and the premature termination of the process, resulting in a stable, continuous capture loop.

Running as a Background Process

To run this capture continuously, you can send it to the background with `nohup` and `&`.

nohup tcpdump -i any -w /tmp/capture.pcap -G 1800 -W 1 -Z root 'host hostname.asd.local and port 12345' &

To stop the capture, find its process ID with `pgrep tcpdump` and use `kill <PID>`. Note that because the process and the file it creates are owned by root, you will need `sudo` to manage them.