【Shell】30分鍾關閉Tcpdump,開啟Tcpdump、檢測目錄大小終止任務


場景

按照一定時間規律運行Tcpdump

思路

編程思路細化思考

查看文件個數

    file_count_results=`ls -al "C:\\Users\\Windows32\\Desktop\\test" | grep ^- | wc -l`

顯示文件大小

$ du -h --max-depth=0
2.1G    .

$ du -bs
2177623726 .

這樣的話,在SHELL里把文件夾大小做為命令輸出賦值到一個變量里,但是用awk命令取第一列

CHECK=$(du -bs /data/sflow_log | awk '{print $1}')

關系運算符

運算符	說明	舉例
-eq	檢測兩個數是否相等,相等返回 true。	[ $a -eq $b ] 返回 false。
-ne	檢測兩個數是否不相等,不相等返回 true。	[ $a -ne $b ] 返回 true。
-gt	檢測左邊的數是否大於右邊的,如果是,則返回 true。	[ $a -gt $b ] 返回 false。
-lt	檢測左邊的數是否小於右邊的,如果是,則返回 true。	[ $a -lt $b ] 返回 true。
-ge	檢測左邊的數是否大於等於右邊的,如果是,則返回 true。	[ $a -ge $b ] 返回 false。
-le	檢測左邊的數是否小於等於右邊的,如果是,則返回 true。	[ $a -le $b ] 返回 true。

判斷文件大小,超過大小終止程序

# 2GB
SIZE="2177622069"

# check the current size
CHECK=$(du -bs | awk '{print $1}')

if [ "$CHECK" -gt "$SIZE" ]; then
       # kill Tcpdump
       kill_tcpdump=$(ps aux | grep tcpdump | awk '{print $2}' | xargs sudo kill -9)
fi

sudo運行bash

$ cat test.sh
#!/bin/foo
echo bar

$ ./test.sh
bash: ./test.sh: /bin/foo: bad interpreter: No such file or directory

$ bash test.sh
bar

$ sudo ./test.sh
sudo: unable to execute ./test.sh: No such file or directory

$ sudo bash ./test.sh
bar

Windows與Linux文件轉換

cat test.sh | col -b > test1.sh

計划任務部分

計划任務實現30分鍾運行一次shell腳本,關閉和開啟TCPdump

#------------crontab
*/30 * * * * /test.sh

shell腳本內容:


# kill Tcpdump

kill_tcpdump=$(ps aux | grep tcpdump | awk '{print $2}' | xargs sudo kill -9)

# run tcpdump ,`date `是時間戳

tcpdump -i eth0 -w `date +%s`.pcap

檢測文件目錄大小

目的是為了檢測文件目錄的文件是不是超出了預估范圍。如果已經超出了預期就停止tcpdump進程

#------------sec shell
# init file_count_results
file_count_results=0

# 1GB
SIZE="1088811863"
while(( $file_count_results<=5 ))
do
    # check the current size
    CHECK=$(du -bs | awk '{print $1}')
    # if file size > 1GB
    if [ "$CHECK" -ge "$SIZE" ]; then
	   # kill Tcpdump,也可以選擇刪除計划任務
       kill_tcpdump=$(ps aux | grep tcpdump | awk '{print $2}' | xargs sudo kill -9)
	   #break
    fi	
	# watch file size
    file_count_results=`ls -al | grep ^- | wc -l`
	echo "current file count: $file_count_results"
done

參考

Linux下的換行符\n\r以及txt和word文檔的使用
一個Linux平台的門羅幣挖礦木馬的查殺與分析
sudo: unable to execute ./script.sh: no such file or directory


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM