定时备份数据库某个表中的部分数据并将该文件通过邮件发送出去
备份数据库表(mysqldump)
语法:
mysqldump -u用户名 -p密码 数据库名 表名 --where="筛选条件" > 导出文件路径
例子:
从zabbix数据库的history表中导出value>10 的数据到 /home/zabbix/history.sql 这个文件中
mysqldump -uzabbix -pzabbix -hlocalhost zabbix history where="value>10">/home/zabbix/history.sql
或者保存成txt文件
mysqldump uzabbix pzabbix hlocalhost zabbix history where="value>10">/home/zabbix/history.txt
备份某一列或某几列
语法:
mysql -u用户名 -p密码 -e "SELECT 列名,列名 INTO OUTFILE ‘/tmp/backup.txt‘ FIELDS TERMINATED BY ‘,‘ OPTIONALLY ENCLOSED BY ‘"‘ LINES TERMINATED BY ‘\n‘ FROM zabbix.history"
相关命令
FIELDS TERMINATED BY ‘,‘ 列分隔符:,
OPTIONALLY ENCLOSED BY ‘"‘ 数据用双引号引用
LINES TERMINATED BY ‘\n‘ 行分隔符
例子:
mysql -uzabbix -pzabbix -e "SELECT value INTO OUTFILE ‘/tmp/backup.txt‘ FROM zabbix.history"
由此数据备份已经完成
将该文件通过邮件发送
确保已经安装mail或者Postfix邮件服务
Mail发送邮件格式
echo "mail conten" | mail -s test [email protected]
发送附件我用mail一直没有发送成功,由此用的mutt发送附件
yum -y install mutt
测试发送邮件,并添加附件
echo "123" | mutt [email protected] -s "456" -a /tmp/backup.txt
发送成功
Mutt语法格式
echo "" 内容
-s 主题
-a 附件,多个附加要使用多个-a
修改发件人信息,伪造发件人信息
Vi ~/.muttrc
[[email protected] ~]# cat ~/.muttrc
set envelope_from=yes
set use_from=yes
set from="[email protected]"
set realname="MySQL"
再次发送,成功~
脚本如下
#!/bin/bash
#Description:Backup part of the database and send mail to leaders;
#Author:MiaoYongbin
#Date:2014-10-23
#Version:1.0
#Mail:[email protected]
MYSQL_USER=zabbix
MYSQL_PASSWORD=zabbix
MYSQL_HOST=localhost
DATABASE=zabbix
TABLE=history
BACKROW=value
MYSQL=$(which mysql)
BACKDIR=/tmp
DATE=`date +%F_%T`
MUTT=$(which mutt)
$MYSQL -u$MYSQL_USER -p$MYSQL_PASSWORD -h$MYSQL_HOST -e "SELECT $BACKROW INTO OUTFILE ‘$BACKDIR/backup_$DATE.txt‘ FROM $DATABASE.$TABLE"
Title=backup_`date +%F_%T`
Contents="This is backup of part of database."
[email protected]
echo "$Contents" | $MUTT $MAIL -s "$Title" -a $BACKDIR/backup_$DATE.txt