练习一: 请按照这样的日期格式(xxxx-xx-xx)每日生成一个文件, 例如生成的文件名为2017-12-20.log, 并且把磁盘的使用情况写到到这个文件中, 不用考虑cron,仅仅写脚本即可

#! /bin/bash d=date +%F logfile=$d.log df -h > $logfile

练习二: 有日志1.log,部分内容如下

112.111.12.248 – [25/Sep/2013:16:08:31 +0800]formula-x.haotui.com “/seccode.php?update=0.5593110133088248″ 200″http://formula-x.haotui.com/registerbbs.php” “Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1;)”
61.147.76.51 – [25/Sep/2013:16:08:31 +0800]xyzdiy.5d6d.com “/attachment.php?aid=4554&k=9ce51e2c376bc861603c7689d97c04a1&t=1334564048&fid=9&sid=zgohwYoLZq2qPW233ZIRsJiUeu22XqE8f49jY9mouRSoE71″ 301″http://xyzdiy.×××thread-1435-1-23.html” “Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)”

统计出每个IP访问量有多少

核心要点

awk、sort、uniq命令

awk '{print $1}' 1.log|sort |uniq -c |sort -n -r

练习三: 写一个脚本计算一下linux系统所有进程占用内存大小的和。

核心要点

  • ps命令用法
  • for循环
  • 加法运算

#!/bin/bash sum=0 for n in ps aux |sed '1d' |awk '{print $6}' do sum=$[$sum+$n] done echo $sum

练习四: 监控远程的一台机器的存活状态,当发现宕机时发一封邮件给你自己。

核心要点

ping -c10 10.10.10.216 通过ping来判定对方是否在线

#!/bin/bash n=ping -c5 10.10.10.216|grep 'packet' |awk -F '%' '{print $1}' |awk '{print $NF}' if [ -z "$n" ] then echo "脚本有问题。" python mail.py $m "检测机器存活脚本$0有问题" "获取变量的值为空" exit else n1=echo $n|sed 's/[0-9]//g' if [ -n "$n" ] then echo "脚本有问题。" python mail.py $m "检测机器存活脚本$0有问题" "获取变量的值不是纯数字" exit fi fi

if m=mmz@qq.com while : do if [ $n -ge 50 ] then python mail.py $m "机器宕机" "丢包率是$n%" fi sleep 30 done

练习五: 找到/123目录下所有后缀名为.txt的文件

  1. 批量修改.txt为.txt.bak
  2. 把所有.bak文件打包压缩为123.tar.gz
  3. 批量还原文件的名字,即把增加的.bak再删除

核心要点

  • find用来查找所有.txt文件
  • tar打包一堆文件
  • 还原文件名用for循环

#!/bin/bash find /123/ -type f -name "*.txt" > /tmp/txt.list for f in cat /tmp/txt.list do mv $f $f.bak done

#find /123/ -type f -name *.txt |xargs -i mv {} {}.bak #find /123/ -type f -name *.txt -exec mv {} {}.bak ;

for f in cat /tmp/txt.list do echo $f.bak done > /tmp/txt.bak.list

tar -czvf 123.tar.gz cat /tmp/txt.bak.list |xargs

for f in cat /tmp/txt.list do mv $f.bak $f done