转载请注明出处:https://blog.csdn.net/l1028386804/article/details/79761984
1、编辑crontab任务
输入
- sudo vi /etc/crontab #编辑crontab任务
修改后的/etc/crontab 内容如下:
- !/bin/sh
- source /etc/profile
- SHELL=/bin/bash
- PATH=/sbin:/bin:/usr/sbin:/usr/bin
- MAILTO=root
- HOME=/
- # For details see man 4 crontabs
- # Example of job definition:
- # .---------------- minute (0 - 59)
- # | .------------- hour (0 - 23)
- # | | .---------- day of month (1 - 31)
- # | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
- # | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
- # | | | | |
- # * * * * * user-name command to be executed
- 59 23 * * * root /usr/local/MysqL/backup/backup.sh >> /usr/local/MysqL/backup/error.log 2>&1
2、编辑备份数据库的脚本
在脚本中输入以下内容
#注:这里不用sudo /usr/local/MysqL/bin/MysqLdump -u 用户名 -p密码 数据库名 | gzip 这种形式,不然会报Warning: Using a password on the command line interface can be insecure. 这里我们将数据库用户名和密码保存在数据的conf配置文件中,例如我的配置文件是/etc/my.cnf,在my.cnf中加入
3、给备份文件夹和脚本文件授权
4、启动或重启crond定时任务
sudo /etc/rc.d/init.d/crond start 启动脚本,如果脚本已经启动则用sudo /etc/rc.d/init.d/crond restart 重启脚本5、遇到的问题
备份脚本手动执行没有任何问题,但是放在crontab定时任务中就出现备份的脚本文件为空,查资料后发现有的人说是因为MysqLdump的路径写的是相对路径,改成绝对路径即可,但是我的路径写的是绝对路径,后面查看error.log日志发现报sudo: sorry,you must have a tty to run sudo 错误。执行 sudo vim /etc/sudoers 将Defaults requiretty 修改为Defaults:nobody !requiretty,表示仅 nobody 用户不需要控制终端。按esc输入::wq!强制保存,这样文件就能正常备份了。