前言
這是我在這個(gè)網(wǎng)站整理的筆記,關(guān)注我,接下來還會(huì)持續(xù)更新。 作者:RodmaChen
數(shù)據(jù)庫備份恢復(fù)功能是每個(gè)產(chǎn)品所需的,以下是簡單的腳本案例,滿足了大部分備份和恢復(fù)需求
關(guān)于備份恢復(fù)命令可參考這篇文章:PostgreSQL – 備份恢復(fù)命令
一. 數(shù)據(jù)庫備份
我創(chuàng)建了back-sql.sh腳本
#!/bin/bash
pg_info=($1)
local_path=$2
ctime=$(date "+%Y%m%d%H%M%S")
backup_path="${local_path}/${ctime}_${pg_info[4]}.sql"
zip_path="${local_path}/${ctime}_sql.zip"
pg_dump --compress=9 --dbname=postgres://${pg_info[0]}:"${pg_info[1]}"@"${pg_info[2]}":${pg_info[3]}/${pg_info[4]} --format=custom --file=${backup_path}
cd ${local_path}/
zip -m ${zip_path} "${ctime}_${pg_info[4]}.sql"
linux上執(zhí)行以下命令就備份成功了
給腳本執(zhí)行權(quán)限
chmod +x back-sql.sh
./back-sql.sh "用戶名 密碼 地址 端口 數(shù)據(jù)庫" 要備份的路徑
這樣就能夠備份成功了
–compress=9是為了給備份出來的文件壓縮,原本備份出來的sql有31M,壓縮后就是3M
–format=custom --file=${backup_path}是備份出二進(jìn)制文件,與pg_restore 配合使用
如果不使用以上兩個(gè)命令,那么就需要psql命令進(jìn)行恢復(fù)
二. 數(shù)據(jù)庫恢復(fù)
我做了點(diǎn)容錯(cuò),處理邏輯如下
創(chuàng)建一個(gè)recover-sql.sh腳本
#!/bin/bash
pg_info=($1)
path=$2
ctime=test_$(date "+%Y%m%d%H%M%S")
sql_path=${path}
psql postgres://${pg_info[0]}:"${pg_info[1]}"@${pg_info[2]}:${pg_info[3]}/postgres <<EOF
CREATE database ${ctime};
EOF
pg_restore --exit-on-error --dbname=postgres://${pg_info[0]}:"${pg_info[1]}"@${pg_info[2]}:${pg_info[3]}/${ctime} ${sql_path}
if [ $? -ne 1 ]; then
echo "pg_restore 命令執(zhí)行成功"
psql postgres://${pg_info[0]}:"${pg_info[1]}"@${pg_info[2]}:${pg_info[3]}/postgres <<EOF
SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = '${pg_info[4]}' AND pid <> pg_backend_pid();
DROP database IF EXISTS ${pg_info[4]};
ALTER database ${ctime} rename to ${pg_info[4]};
EOF
else
echo "pg_restore 命令執(zhí)行失敗"
psql postgres://${pg_info[0]}:"${pg_info[1]}"@${pg_info[2]}:${pg_info[3]}/postgres <<EOF
DROP database IF EXISTS ${ctime};
EOF
fi
linux上執(zhí)行以下命令就恢復(fù)成功了
./recover-sql.sh "用戶名 密碼 地址 端口 數(shù)據(jù)庫" 你sql文件的地址(列如:/tmp/hwaf2/b.sql)
三. 存留問題
- 備份出來的數(shù)據(jù)庫是明文的,可以被隨意查看的
- 可以隨便拿一個(gè)sql就能進(jìn)行恢復(fù),修改掉原來的數(shù)據(jù)庫
針對(duì)以上問題,我的方案是對(duì)sql文件進(jìn)行加密。
我通過python使用國密的sm2和sm4進(jìn)行了嘗試,發(fā)現(xiàn)如果sql文件過大,加密速度變得很慢,所以這種加密方法明顯行不通,不知道各位大神有什么解決方案文章來源:http://www.zghlxwxcb.cn/news/detail-610556.html
作者:RodmaChen
本人博客:https://blog.csdn.net/weixin_46654114
轉(zhuǎn)載說明:務(wù)必注明來源,附帶本人博客連接。文章來源地址http://www.zghlxwxcb.cn/news/detail-610556.html
到了這里,關(guān)于PostgreSQL--實(shí)現(xiàn)數(shù)據(jù)庫備份恢復(fù)詳細(xì)教學(xué)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!