mysqldump 成功后发送电子邮件

mysqldump 成功后发送电子邮件

我有一个脚本,它将通过 mysqldump 备份 mysql db。我想在这个脚本中添加另一个选项,以便在转储成功或失败时自动发送电子邮件。

脚本如下:

#!/bin/sh
BACKUP=/data/backup/sql2/new_backup/daily
cd $BACKUP
mkdir `date '+%d-%m-%Y'`
NOW=$(date +"%d-%m-%Y")

MUSER="root"
MPASS="mypass"
MHOST="sql4"
MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
GZIP="$(which gzip)"

DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"
for db in $DBS
do
 FILE=$BACKUP/$NOW/mysql-$db.$NOW-$(date +"%T").sql.gz
 $MYSQLDUMP -u $MUSER -h $MHOST -p$MPASS --lock-all-tables $db | $GZIP -9 > $FILE
done

我怎样才能做到这一点?

答案1

mysqldump0如果一切顺利, 将以退出代码结束。您可以使用:

#!/bin/sh
BACKUP=/data/backup/sql2/new_backup/daily
cd $BACKUP
mkdir `date '+%d-%m-%Y'`
NOW=$(date +"%d-%m-%Y")

MUSER="root"
MPASS="mypass"
MHOST="sql4"
MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
GZIP="$(which gzip)"
MAIL="[email protected]"
MAILER="$(which mail)"
STATUSFILE="/tmp/statusfile.$NOW"


echo "Backup report from $NOW" > $STATUSFILE
DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"
for db in $DBS
do
 FILE=$BACKUP/$NOW/mysql-$db.$NOW-$(date +"%T").sql.gz
 $MYSQLDUMP -u $MUSER -h $MHOST -p$MPASS --lock-all-tables $db | $GZIP -9 > $FILE
 if [ "$?" -eq "0" ] then; 
   echo "$db backup is OK" >> $STATUSFILE
  else 
   echo "##### WARNING: #####  $db backup failed" >> $STATUSFILE
  fi
done
$MAILER -s "Backup report for $NOW" -- $MAIL < $STATUSFILE
rm $STATUSFILE

我还没有测试过,但这是一般的做法。

答案2

#!/bin/bash 

TO="[email protected]" 
SUBJECT="testmail"      
MSG="bla bla bla"

/usr/sbin/sendmail -t <<EOF
to:$TO
subject:$SUBJECT
$MSG
EOF

如果需要,您还可以添加“发件人”字段。

相关内容