每隔5min备份一次/etc目录,存放到/backup目录下, 备份成功之后产生“2018-08-13 14:09 etc directory backup successfully”

[root@kvm1 ~]# vim /etc/rsyslog.conf 
....
local2.*                /var/log/back.log
[root@kvm1 ~]# systemctl restart rsyslog

编写脚本,实现备份和日志
[root@kvm1 ~]# vim back.sh 
#!/usr/bin/env bash di
if test ! -d /backup ;then
    mkdir /backup
fi
tar -czf /backup/etc_`date +%M`.tar.gz  /etc &>/dev/null
logger -p local2.info -t back  "`date +%F` `date +%R` etc directory backup successfully"

[root@kvm1 ~]# chmod +x back.sh 

测试脚本
[root@kvm1 ~]# ./back.sh 
[root@kvm1 ~]# ll /backup/
total 204208
-rw-r--r-- 1 root root        0 Jul 31 15:11 abc.txt.bak
-rw-r--r-- 1 root root 74956733 Aug 21 20:56 etc_56.tar.gz

[root@kvm1 ~]# date
Tue Aug 21 20:57:49 CST 2018

[root@kvm1 ~]# ll /var/log/back.log 
-rw------- 1 root root 222 Aug 21 20:56 /var/log/back.log

[root@kvm1 ~]# tail /var/log/back.log 
Aug 21 20:54:54 gaojingbo back: 5420:54 etc directory backup successfully
Aug 21 20:55:20 gaojingbo back: 5520:55 etc directory backup successfully
Aug 21 20:56:44 gaojingbo back: 5620:56 etc directory backup successfully

[root@kvm1 ~]# chattr +i back.sh 

设定计划任务
[root@kvm1 ~]# crontab -e
no crontab for root - using an empty one
crontab: installing new crontab
[root@kvm1 ~]# crontab -l
*/5 * * * * /root/back.sh
[root@kvm1 ~]# date
Tue Aug 21 21:00:30 CST 2018
[root@kvm1 ~]# tail -f /var/log/cron
Aug 21 21:05:01 gaojingbo CROND[15062]: (root) CMD (/root/back.sh)

查看计划任务是否执行
[root@kvm1 ~]# tail -1 /var/log/cron
Aug 17 08:30:01 kvm1 CROND[22572]: (root) CMD (/root/back.sh)

检查计划任务执行之后的结果
[root@kvm1 ~]# ll /backup/
total 146400
-rw-r--r-- 1 root root        0 Jul 31 15:11 abc.txt.bak
-rw-r--r-- 1 root root 74956733 Aug 21 21:05 etc_05.tar.gz
-rw-r--r-- 1 root root 74956733 Aug 21 20:56 etc_56.tar.gz

[root@kvm1 ~]# cat /var/log/back.log 
Aug 21 20:54:54 kvm1 back: 5420:54 etc directory backup successfully
Aug 21 20:55:20 kvm1 back: 5520:55 etc directory backup successfully
Aug 21 20:56:44 kvm1 back: 5620:56 etc directory backup successfully
Aug 21 21:05:08 kvm1 back: 0521:05 etc directory backup successfully



编写日志伦准规则文件,从而实现定期的对日志进行轮转
对你的日志编写轮转规则文件,要求日志文件需要有a属性
[root@kvm1 ~]# cd /etc/logrotate.d/
[root@kvm1 logrotate.d]# vim back
/var/log/back.log {
    prerotate
    chattr -a /var/log/back.log
    endscript

    notifempty
    size 30k
    hourly
    create 0600 root root
    rotate 2

    postrotate
    chattr +a /var/log/back.log
    endscript
}
[root@kvm1 logrotate.d]# crontab -e
crontab: installing new crontab
[root@kvm1 logrotate.d]# crontab -l
*/5 * * * *     /root/back.sh
01 * * * *      /usr/sbin/logrotate  -f  /etc/logrotate.d/back

你可能感兴趣的:(linux基础)