如何使用sngrep -O按小时轮转捕获文件并正确命名?
Got it, let's work through this issue! The core problem here is that sngrep doesn't natively support strftime-style placeholders like %H in its -O output filename parameter (unlike tcpdump, which handles those format strings automatically). That's why it's saving files as literal file%H.pcap instead of replacing %H with the current hour.
Here's how to get the hourly-named files you want, paired with timeout to capture exactly 1 hour of traffic each time:
One-Time Hourly Capture
If you just need a single 1-hour capture with the current hour in the filename, use shell command substitution to grab the hour first, then pass it to sngrep:
# Capture for 1 hour, save to fileXX.pcap where XX is the current 2-digit hour timeout 1h sngrep -O file$(date +%H).pcap
date +%Houtputs the current hour as a 2-digit number (00 to 23)- The shell replaces
$(date +%H)with that number before running sngrep, so your filename will end up likefile08.pcaporfile19.pcap
Continuous Hourly Rotation (Loop)
If you want to keep generating hourly capture files automatically (one every hour, indefinitely), wrap the command in a simple shell loop:
while true; do # Grab the current hour right before starting each capture CURRENT_HOUR=$(date +%H) # Run sngrep for 1 hour with the hour-specific filename timeout 1h sngrep -O file${CURRENT_HOUR}.pcap # Optional: Add a short sleep to avoid overlapping captures if timeout is slightly off sleep 10 done
- This loop starts a new capture every hour, using the hour at the start of each window for the filename.
- Note: Packet capture requires root privileges, so you'll probably need to run this with
sudo(e.g.,sudo bash -c 'while true; do ... done'or run the script as root).
Quick Additional Tips
- If you need to capture traffic from a specific interface, add the
-iflag (e.g.,sngrep -i eth0 -O ...for interface eth0). - You can also append BPF filters to the end of the sngrep command to narrow down the traffic you capture (e.g.,
sngrep -O file$(date +%H).pcap port 5060for SIP traffic).
内容的提问来源于stack exchange,提问作者user3616515

