Shell練習(十一)
阿新 • • 發佈:2018-03-07
linux shell 習題1:統計數字並求和
要求:計算文檔1.txt中每一行中出現的數字個數並且要計算一下整個文檔中一共出現了幾個數字。
參考答案:
#!/bin/bash # date:2018年3月6日 sum=0 for i in `cat /root/2.txt` do line=`echo -n "$i"|sed 's/[^0-9]//g'|wc -c` sum=$[$sum+$line] done echo $sum
習題2:統計網卡流量
要求:寫一個腳本,檢測你的網絡流量,並記錄到一個日誌裏。需要按照如下格式,並且一分鐘統計一次(只需要統計外網網卡,假設網卡名字為eth0):
2017-08-04 01:11
eth0 input: 1000bps
eth0 output : 200000bps
-----------------------------
2017-08-04 01:12
eth0 input: 1000bps
eth0 output : 200000bps
提示:使用sar -n DEV 1 59 這樣可以統計一分鐘的平均網卡流量,只需要最後面的平均值。另外,註意換算一下,1byt=8bit
參考答案:
#!/bin/bash # date:2018年3月6日 while : do d=`date +"%F %T"` logfile=/tmp/ens33.txt [ -f $logfile ] || touch $logfile echo $d >> $logfile sar -n DEV 1 59|grep "平均時間"|grep "ens33"|awk '{print $2" input\t"$3*1000*8"bps\n"$2" output\t"$4*1000*8"bps"}'>>$logfile echo "------------------------------" >> $logfile done
習題3:批量殺死進程
要求:由於clearmem.sh腳本導致網站訪問變慢,編寫腳本殺死此腳本。
參考答案:
ps aux|grep clearmem.sh|grep -v grep|awk '{print $2}'|xargs kill
Shell練習(十一)