摘要
使用tcpdump抓UDP包,過濾過濾IP和port,并且自動拆分片段。
安裝tcpdump
yum install -y tcpdump
使用方法
tcpdump -i bond0 udp port xxxx and host xxx.x.xx.xxx -s0 -G 600 -w %Y_%m%d_%H%M_%S.pcap
參數說明
-i 指定監聽的網卡
udp 監聽UDP協議
port 指定過濾的端口
host 指定過濾的ip
-s *表示*從一個包中截取的字節數,*0表示*包不截斷
-G 按照固定的時間間隔切割輸出的文件(單位:秒)
-w 直接將包寫入文件中,并不分析和打印出來;
取非運算是 ‘not ’ ‘! ‘,與運算是’and’,’&&;或運算 是’or’ ,‘||’
定時抓包(python)
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# @author 張文兵
# @blog https://zhangwenbing.com/
# @datetime 2020-12-18 14:56:01
# @description
#
import os
import time
from apscheduler.schedulers.blocking import BlockingScheduler
def system(cmd):
t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
print('{} 執行 {}'.format(t, cmd))
stat = os.system(cmd)
if stat != 0:
print('{} 執行 {} 失敗'.format(t, cmd))
scheduler = BlockingScheduler()
# 星期1-5的17點40分執行抓包任務
scheduler.add_job(system, 'cron', day_of_week="mon,tue,wed,thu,fri,sat",
hour=17, minute=30, args=['/sbin/tcpdump -i bond0 udp port xxxx and host xxx.x.xx.xxx -s0 -G 3600 -w /your_path/%Y_%m%d_%H%M_%S.pcap &>/dev/null'])
# 星期1-5的20點01分執行kill
scheduler.add_job(system, 'cron', day_of_week="mon,tue,wed,thu,fri,sat",
hour=20, minute=1, args=['pkill -9 tcpdump &>/dev/null'])
scheduler.start()
# 星期1-5的23點59分執行自動清理7天之前的抓包文件
scheduler.add_job(system, 'cron', day_of_week="mon,tue,wed,thu,fri,sat",
hour=23, minute=59, args=['/usr/bin/find /your_path/ -type f -ctime +7 -exec rm -f {} \; &>/dev/null'])
scheduler.start()
切分抓包文件
tcpdump -r old_file -w new_files -C 10
-r 指定需要切分的文件
-w 指定新的文件名前綴
-C 指定切分的文件大小(單位:M)