shell-实战-收集日志入库(mysql)-发送邮件(mail)

  1. backupdb.sh
#!/bin/bash

sql_file=`date +%Y%m%d`.sql
init_sql(){
[ -f "$sql_file" ] && rm -f "$sql_file"
for logfile in `find . -name "*.log" -mtime 0`;
do
    msg=`tail -1 $logfile`
    flat=`echo $msg | cut -d "," -f1`
    mail=`echo $msg | cut -d "," -f7`
    #[email protected]
    if [[ "$flat" != 'true' ]];
    then
        echo $msg | mail -s "数据备份未成功,请检查" "$mail"
    fi
    msg=`echo $msg | awk -F "," '{OFS="+"}{$6="str_to_date(\""$6"\",\"%Y%m%d%H%i\")";print $0}'`
    for i in 1 2 3 4 5 7 8;do
    msg=`echo $msg | awk -F "+" -v var="$i" '{OFS="+"}{$var="\""$var"\"";print $0}'`
    done
    echo "$msg" >> $sql_file
done
sed -i "s/+/,/g" "$sql_file"
sed -i "s/^/insert into backup_report values\(null,/g" "$sql_file"
sed -i "s/$/\);/g" "$sql_file"
}

mysql_insert(){
my_user=root
my_pw=dagasga
my_host=1.1.1.1
my_instance=dfadfag

mysql -u"$my_user" -p"$my_pw" -h"$my_host" -s "$my_instance" < "$1"
}

#init_sql
init_sql && mysql_insert "$sql_file"
  1. 'vim /etc/mail.rc'
# set from=drfung\@qq.com smtp="smtp.exmail.qq.com:465"
# set smtp-auth-user=drfung\@qq.com smtp-auth-password=dfasdfagfa smtp-auth=login
# set ssl-verify=ignore

set from=drfung\@163.com smtp="smtp.163.com"
set smtp-auth-user=drfung\@163.com smtp-auth-password=dfadagg smtp-auth=login
  1. crontab设置,每天6点定时执行
0 6 * * * bash /backuplog/backup_db.sh

你可能感兴趣的:(shell-实战-收集日志入库(mysql)-发送邮件(mail))