Linux定时自动备份pg数据库

  • 编写备份数据库shell脚本:vi db_backup.sh
#!/bin/bash
dbname=$(date +%Y%m%d_back.sql)
pg_dump -h 127.0.0.1 -p 6688 -U shtecdba -d shtec -n shtecdba -O > /home/yt/back_sql/$dbname
  • 设置备份pg数据库时免密登陆
    命令:vi ~/.pgpass(在当前目录下创建密码隐藏文件)
#hostname:port:database:username:password
127.0.0.1:6688:sh:dba:123456
  • 编辑完成设置权限(否则会报错):chmod 0600 ~/.pgpass
    给备份shell脚本添加执行权限:chmod -R 777 db_backup.sh
  • 设置定时任务(周一到周五每天凌晨3点执行数据库备份)
    查看cron服务状态:service crond status
    当前用户下编写定时任务命令:crontab -e
00 3 * * 1-5 /root/db_backup.sh >/dev/null 2>&1
  • 使用rsync进行文件增量备份:
    安装rsync步骤:
    1.下载:wget https://download.samba.org/pub/rsync/src/rsync-3.1.2.tar.gz
    2.解压:tar -xvf rsync-3.1.2.tar.gz
    3.进入解压后目录
    4.配置安装路径:./configure --prefix=/usr/local/rsync
    5.编译:make
    5.安装:make install
    6.配置conf文件:vi /usr/local/rsync/rsync.conf
    配置文件内容:
uid = root
gid = root
use chroot = yes
strict modes = false
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
####
log file = /var/log/rsyncd.log
transfer logging = true
log format= "%o [%a] %m (%u) %f %l %b %c"
##
reverse lookup = no
ignore errors = true
read only = false
hosts allow = 10.196.222.14
hosts deny = 0.0.0.0/0.0.0.0
strict modes = yes
list = false
max connections = 10
timeout = 1800
[backup]
path = /home/yt
auth users = root
secrets file = /usr/local/rsync/rsyncd.secrets

7.修改密码文件权限

chmod 600 /usr/local/rsync/rsyncd.secrets

8.启动服务

/usr/local/rsync/bin/rsync --daemon --config=/usr/local/rsync/rsync.conf
  • 备份同步语句
rsync -vrtopg --ignore-existing --delete  [email protected]::backup /home/yt --password-file=/etc/rsyncd.passwd
  • 编写增量备份脚本:vi back_sync.sh
#!/bin/bash
#数据备份同步(增量备份)
rsync -vrtopg --ignore-existing --delete  [email protected]::backup /home/yt --password-file=/etc/rsyncd.passwd
#数据库还原
dbname=$(date +%Y%m%d_back.sql)
psql -U shtecdba -d shtec -h 127.0.0.1 -p 6688 -f /home/yt/back_sql/$dbname
  • 设置定时增量备份:crontab -e
00 4 * * 1-5 /root/back_sync.sh >/dev/null 2>&1

你可能感兴趣的:(Linux定时自动备份pg数据库)