基于Tcpdump自动抓包存储脚本

#!/bin/bash

# 指定 TCPdump 输出文件名和路径。
# 这里使用当前目录下的 tcpdump_output 文件。
output_file="tcpdump_output"

# 待关闭的 TCPdump 进程 PID
tcpdump_cur_pid=
tcpdump_pre_pid=

# 指定每个文件的最大大小,以 M 为单位。
max_size=30

# 实际大小计量单位: 字节
max_bytes=$((${max_size} * 1024 * 1024))

# 指定要保留的文件数量上限。
max_files=10

mv "${output_file}" "${output_file}_$(date +%Y%m%d-%H%M%S).txt"

tcpdump -tttt -n -i any udp >> "${output_file}" &
tcpdump_cur_pid=$!
tcpdump_pre_pid=${tcpdump_cur_pid}

while true; do
  # 获取输出文件的当前大小(单位:字节)。
  file_size=$(stat -c%s ${output_file})

  # 如果文件大小超过了指定大小,则创建新的输出文件,
  # 并将TCPdump命令的输出重定向到新文件。
  if [[ "${file_size}" -ge "${max_bytes}" ]]; then
	mv "${output_file}" "${output_file}_$(date +%Y%m%d-%H%M%S).txt"
 
	# 启动 TCPdump 命令,将输出重定向至新的指定文件。
    # 输出包括时间戳和所有数据包。
    tcpdump -tttt -n -i any udp >> "${output_file}" &
    tcpdump_cur_pid=$!

    # echo "Started capture with PID=${tcpdump_cur_pid}"
	
	# 在启动Tcpdump之后,关闭之前的进程
    if [[ -n "${tcpdump_pre_pid}" ]]; then
		
        # echo "Stopping capture with PID=${tcpdump_pre_pid}"
        kill ${tcpdump_pre_pid}
		tcpdump_pre_pid=${tcpdump_cur_pid}
    fi

  fi
 
  # 删除旧的输出文件以保持指定数量上限。
  file_count=$(ls -A ${PWD} | grep ^tcpdump_output_ | wc -l)
  if [[ "${file_count}" -gt "${max_files}" ]]; then
     # echo "File count (${file_count}) is greater than limit (${max_files}). Removing oldest file."
     oldest_file=$(ls -tr1 ${PWD} | grep ^tcpdump_output_ | head -1)
     rm -f ${oldest_file}
  fi
      
  # 等待一秒钟再次检查文件大小和数量。
  sleep 1

done

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值