实验:
需求:两类机器一共300多台,写个脚本自动清理这两类机器里面的日志文件。在堡垒机批量发布,也要批量发布到crontab里面。
A类机器日志存放路径很统一,B类机器日志存放路径需要用匹配(因为这个目录里除了日志外,还有其他文件,不能删除。匹配的时候可用.log)
A类:/opt/cloud/log/ 删除7天内的
B类: /opt/cloud/instances/ 删除15天内的
要求写在一个脚本里面。不用考虑堡垒机上的操作,只需要写出shell脚本
第一台机器
[root@localhost ~]# cd /opt
[root@localhost opt]# mkdir cloud
[root@localhost opt]# cd cloud/
[root@localhost cloud]# mkdir log
[root@localhost cloud]# cd log/
[root@localhost log]# touch 1.log 2.log
[root@localhost log]# ll
total 0
-rw-r--r-- 1 root root 0 Aug 25 22:18 1.log
-rw-r--r-- 1 root root 0 Aug 25 22:18 2.log
[root@localhost log]# ll
total 0
-rw-r--r-- 1 root root 0 Aug 25 22:13 1.log
-rw-r--r-- 1 root root 0 Aug 25 22:13 2.log
[root@localhost ~]# vi shanchurizhi.sh
#!/bin/bash
d1=/opt/cloud/log/
d2=/opt/cloud/instances/
if [ -d $d1 ];then
find $d1 -type f -mtime -7 -exec rm -rf {} \;
echo "已删除7天内的日志!"
elif [ -d $d2 ];then
find $d2 -name "*.log" -type f -mtime -15 -exec rm -rf {} \;
echo "已删除15天内的日志!"
fi
[root@localhost ~]# . shanchurizhi.sh
已删除7天内的日志!
[root@localhost ~]# cd /opt/cloud/log/
[root@localhost log]# ll
total 0 ##.log文件已被删除
第二台机器
[root@localhost ~]# cd /opt
[root@localhost opt]# mkdir cloud
[root@localhost opt]# cd cloud/
[root@localhost cloud]# mkdir instances
[root@localhost cloud]# cd instances/
[root@localhost instances]# touch 1.log 2.log 1.txt 2.txt
[root@localhost instances]# ll
total 0
-rw-r--r-- 1 root root 0 Aug 25 02:24 1.log
-rw-r--r-- 1 root root 0 Aug 25 02:24 1.txt
-rw-r--r-- 1 root root 0 Aug 25 02:24 2.log
-rw-r--r-- 1 root root 0 Aug 25 02:24 2.txt
[root@localhost ~]# vi shanchurizhi.sh
#!/bin/bash
d1=/opt/cloud/log/
d2=/opt/cloud/instances/
if [ -d $d1 ];then
find $d1 -type f -mtime -7 -exec rm -rf {} \;
echo "已删除7天内的日志!"
elif [ -d $d2 ];then
find $d2 -name "*.log" -type f -mtime -15 -exec rm -rf {} \;
echo "已删除15天内的日志!"
fi
[root@localhost ~]# . shanchurizhi.sh
已删除15天内的日志!
[root@localhost ~]# cd /opt/cloud/instances/
[root@localhost instances]# ll
total 0
-rw-r--r-- 1 root root 0 Aug 25 02:24 1.txt
-rw-r--r-- 1 root root 0 Aug 25 02:24 2.txt #除了.log格式文件外其他文件不能删除