hwl198212 发表于 2018-8-17 09:08:02

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 DEV1 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

页: [1]
查看完整版本: Shell练习(十一)