2017/11/15 周三;
天气: 小雨!
1、需求:
设计一个shell脚本来备份数据库,首先在本地服务器上保存一份数据,然后再远程拷贝一份,本地保存一周的数据,远程保存一个月。
假定,我们知道mysql root账号的密码,要备份的库为discuz,本地备份目录为/bak/mysql, 远程服务器ip为192.168.123.30,远程提供了一个rsync服务,备份的地址是 192.168.123.30::backup . 写完脚本后,需要加入到cron中,每天凌晨3点执行。
[root@Dasoncheng sbin]# cat g2.sh
#!/bin/bash
#Backup the mysql localhost saved for a weekday;
#And send it remote saved for a month;
PATH=$PATH:/usr/local/mysql/bin
d1=`date +%w`
d2=`date +%d`
pass=p@ssw0rd
bakdir=/tmp/mysql
r_bakdir=192.168.60.12::test/mysql
#exec 1>/var/log/mysqlbak.log 2>/var/log/mysqlbak.log
echo "mysql backup begin at `date +"%F %T"`"
mysqldump -uroot -p$pass --default-character-set=gbk zabbix >$bakdir/$d1.sql
rsync -azP --port 8730 $bakdir/$d1.sql $r_bakdir/$d2.sql
echo "mysql backup end at `date +"%F %T"`"
[root@Dasoncheng sbin]# crontab -e ##定时任务;
crontab: installing new crontab
0 3 * * * /bin/sh /usr/local/sbin/g2.sh
2、需求:
服务器上跑的是LNMP环境,近期总是有502现象。502为网站访问的状态码,200正常,502错误是nginx最为普通的错误状态码。由于502只是暂时的,并且只要一重启php-fpm服务则502消失,但不重启的话,则会一直持续很长时间。所以有必要写一个监控脚本,监控访问日志的状态码,一旦发生502,则自动重启一下php-fpm。
我们设定:
- access_log /data/log/access.log
- 脚本死循环,每10s检测一次(假设每10s钟的日志条数为300左右)
- 重启php-fpm的方法是 /etc/init.d/php-fpm restart
[root@Dasoncheng sbin]# cat h.sh
#!/bin/bash
log=/data/log/access.log
N=10
while :;
do
##Because it generates about three hundreds of logs; so
tail -n 300 $log > /tmp/log
n_502=`grep -c '502' /tmp/log`
if [ $n_502 -ge $N ];
then
##Recording the status of system;
top -bn1 > /tmp/`date +%H%M%S`-top.log
vmstat 1 5 > /tmp/`date +%H%M%S`-vm.log
/etc/init.d/php.fpm restart 2>/dev/null
##You should sleep 1 minute after the php-fpm restarted ,then test it once every ten seconds;
sleep 60
fi
sleep 10
done
参考答案:
1、
#! /bin/bash
### backup mysql data
### Writen by Aming.
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/mysql/bin
d1=`data +%w`
d2=`date +%d`
pass=”your_mysql_password”
bakdir=/bak/mysql
r_bakdir=192.168.123.30::backup
exec 1>/var/log/mysqlbak.log 2>/var/log/mysqlbak.log
echo “mysql backup begin at `date +”%F %T”`.”
mysqldump -uroot -p$pass –default-character-set=gbk discuz >$bakdir/$d1.sql
rsync -az $bakdir/$d1.sql $r_bakdir/$d2.sql
echo “mysql backup end at `date +”%F %T”`.”
然后加入cron
0 3 * * * /bin/bash /usr/local/sbin/mysqlbak.sh
2、
[root@Dasoncheng sbin]# sed '/^$/d' 2.txt ##这个是删除文档空行的一种方法;
#! /bin/bash
log=/data/log/access.log
N=10
while :; do
##因为10秒钟大概产生300条日志
tail -n 300 $log > /tmp/log
n_502=`grep -c ‘ 502″‘ /tmp/log`
if [ $n_502 -ge $N ]; then
##记录系统的状态
top -bn1 >/tmp/`date +%H%M%S`-top.log
vmstat 1 5 >/tmp/`date +%H%M%S`-vm.log
/etc/init.d/php-fpm restart 2>/dev/null
##重启php-fpm服务后,应先暂缓1分钟,而后继续每隔10s检测一次
sleep 60
fi
sleep 10
done