直接在安装有postgres psql和pg_dump的linux服务器上,直接脚本即可一键备份数据库到新建的bak2022xxxxxdbname数据库,同时生成**.sql备份文件。
使用psql(创建新库、备份数据到新的库)、pg_dump(备份数据到**.sql文件)工具命令
使用expect工具(与bash工具类似)命令,自动填充密码
bakDatabase.sh文件
#!/bin/bash # description: Backing up the Database # time: 2022.02.12 # author: wanyu # example: sh bakDatabase.sh dbname # 目标数据库信息 ip地址、端口、用户名、密码、缓存路径 address=127.0.0.1 port=5432 user=postgres password=XXXXX directory=/home/postgres/postgresBakDb/ # 1,创建目录(成功) echo "<1>,Create a directory {$directory}!" mkdir -p "$directory""log" # 2,拼接备份数据库名称(成功) echo "<2>,Splice the name of the backup database -- {$bakdbname}!" dbname=$1 date_format=`date +%Y%m%d%H%M` bakdbname="bak""$date_format""_""$dbname" logDirectory="$directory"log/info.log bakFileDirectory="$directory""$bakdbname"".sql" # 3,备份数据库(成功) echo "<3>,Backing up the Database {$bakdbname} !" expect <<EOF #!/bin/expect set timeout 60 spawn pg_dump -h $address -p $port -U $user -W -f $bakFileDirectory -d $dbname expect "*assword:" {send "$password\r"} expect eof EOF # 4,创建备份数据库 echo "<4>,Creating a backup database {$bakdbname}!" expect <<EOF #!/bin/expect set timeout 60 spawn psql -h $address -p $port -U $user -W expect "*assword:" {send "$password\r"} expect "postgres=# " { send "CREATE DATABASE \"$bakdbname\";\r" send "\\\q\r" } expect eof EOF # 5,恢复备份数据库 echo "<5>,Restore backup database {$bakdbname} data !" restoreData="psql -h $address -p $port -U $user -W -d $bakdbname -f $bakFileDirectory >& $logDirectory" expect <<EOF #!/bin/expect set timeout 60 spawn $restoreData expect "*assword:" {send "$password\r"} expect eof EOF
解决办法:服务器A上的pg_dump版本 >= 服务器B上postgres版本
apt-get install expect