在 tcpdump 中定期删除输出后重新生成输出

Regenerating the output after deleting it in periodic way in tcpdump

我需要使用 tcpdump 监控网络。但是,我需要每 5 秒从其文件夹中手动删除其输出(train.txt)。我正在寻找一种在 bash 文件中重新生成输出的方法。换句话说,当我删除 tcpdump 的输出时,它会生成一个包含新内容的新输出。这是我的代码:

#!/bin/bash
FILE="/media/sf_sharedsaeed/train.txt"
#Change the eth for each host first
tcpdump -i h1-eth0 -l -e -n 'port 80' & > /media/sf_sharedsaeed/train.txt
while true
do
if [ -f $FILE ]; then
   echo "******************* tcpdump do its job well******************* "
else
    #now interrupt the process. get its PID:
    pid=$(ps -e | pgrep tcpdump)
    echo $pid

    kill -2 $pid
    echo "File $FILE does not exist. tcpdump make it again."
    tcpdump -i h1-eth0 -l -e -n  > /media/sf_sharedsaeed/train.txt

fi

done

问题在于,由于删除了输出,因此不再生成新的输出文件。请帮我。

更新: 我使用这段代码来删除文件内容而不是删除文件:(使用 cat /dev/null > $FILE)

#!/bin/bash
FILE="train.txt"
second=5

while true
do
awk '{print " "}' $FILE | sort | uniq -c > output.txt
echo "New output.txt generated."
#truncate -s 0 $FILE
cat /dev/null > $FILE
echo "wait for 5 seconds ..."
sleep $second
done

因为我使用它,输出(train.txt)没有完全填充。一些数据会丢失!

重定向运算符>呢?

cat /dev/null > train.txt

这样您只是截断文件 train.txt,即:将其大小设置为零。

理想情况下,写入 train.txt 的进程应该以 append 模式打开此文件(即:通过 >> 中的重定向运算符 bash). 如果是这样,此进程将始终在写入文件之前将其 文件偏移量 设置为文件的大小。 否则,在下次写入 train.txt.

时,将创建一个所谓的 file hole

基本上:

tcpdump -i h1-eth0 -l -e -n 'port 80' & >> /media/sf_sharedsaeed/train.txt

并且,删除train.txt,改为执行此操作(即:截断文件):

cat /dev/null > /media/sf_sharedsaeed/train.txt

注意:

您可以定期检查其大小,然后在文件太大时根据需要将其截断,而不是手动截断 tain.txt