Search code examples
bashfileawktcpdump

Regenerating the output after deleting it in periodic way in tcpdump


I need to monitoring the network using a tcpdump. However I need to delete its output(train.txt) every 5 seconds from its folder manually. I am looking for a approach to regenerate the output in a bash file. In other words, as I delete the output of tcpdump, it generates a new output with new contents. Here is my code:

#!/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

The problem is that, as the output deleted, no new output file generated anymore. Please help me.

Update: I used this code to delete the file content instead of deleting the file: (using cat /dev/null > $FILE)

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

while true
do
awk '{print $10" "$12}' $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

As I used it, the output(train.txt) is not fill completely. Some data will missed!


Solution

  • What about the redirection operator >?

    cat /dev/null > train.txt
    

    This way you are just truncating the file train.txt, i.e.: setting its size to zero.

    Ideally, the process writing to train.txt should have opened this file in append mode (i.e.: by means of the redirection operator >> in bash). If so, this process will always set the its file offset to the size of the file before writing it. Otherwise a so called file hole would be created the next time it writes to train.txt.


    Basically:

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

    and, do not delete train.txt, do this instead (i.e.: truncate the file):

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

    Note:

    Instead of truncating tain.txt manually you could periodically check its size and then truncate it on demand when the file it's too big.