Linux下oracle数据库本地备份
背景:oracle19c、linux、数据库备份
一、编写备份脚本并授权
#引用环境变量;如果不引用环境变量可能会导致定时任务导出空包
#!/bin/bash
source /etc/profile
source ~/.bash_profile
#脚本正文
export DATA_DIR=/backup
export LOGS_DIR=/backup
export DELTIME=`date -d "5 days ago" +%Y%m%d`
export BAKUPTIME=`date +%Y%m%d%H%M%S`
echo "Starting bakup..."
echo "Bakup file path $DATA_DIR/$BAKUPTIME.dmp"
#写上你自己的用户名/密码;如有@等特殊字符,加'""' 如 'smpm/"Mpm@1234"'
expdp smpm/Mpm1234 dumpfile=$BAKUPTIME.dmp log=$BAKUPTIME.log directory=mydata schemas=smpm;
echo "backup file success..."
tar -zcvPf $DATA_DIR/$BAKUPTIME.tar.gz $DATA_DIR/$BAKUPTIME.dmp $DATA_DIR/$BAKUPTIME.log --remove-files
echo "tar the file bakup successfully. "
find $DATA_DIR -name "*.gz" -ctime +5 -exec rm -rf {} \;
echo "Bakup completed."
注意:脚本中directory需要和前面的/backup路径一直;创建directory如下
#创建directory
CREATE DIRECTORY mydata AS '/backup';
#查询directory:
SELECT * from dba_directories;
使用root账户授予脚本执行权限
[root@localhost ~]# cd /home/oracle/
[root@localhost oracle]# ll
总用量 52
-rw-r-----. 1 oracle oinstall 26499 8月 3 15:20 dbca.rsp
-rw-r--r--. 1 oracle oinstall 19872 8月 3 15:14 db.rsp
drwxr-xr-x 2 oracle oinstall 89 9月 11 17:42 oracledmp
-rwxr-xr-x 1 oracle oinstall 652 9月 12 13:51 P_DB_BAK.sh
drwxr-xr-x. 2 oracle oinstall 6 8月 3 15:12 公共
drwxr-xr-x. 2 oracle oinstall 6 8月 3 15:12 模板
drwxr-xr-x. 2 oracle oinstall 6 8月 3 15:12 视频
drwxr-xr-x. 2 oracle oinstall 6 8月 3 15:12 图片
drwxr-xr-x. 2 oracle oinstall 6 8月 3 15:12 文档
drwxr-xr-x. 2 oracle oinstall 6 8月 3 15:12 下载
drwxr-xr-x. 2 oracle oinstall 6 8月 3 15:12 音乐
drwxr-xr-x. 2 oracle oinstall 6 8月 3 15:12 桌面
[root@localhost oracle]# pwd
/home/oracle
[root@localhost oracle]# chmod +x P_DB_BAK.sh
备份目录/backup的属主需要为oracle,属组要为oninstall,命令为:
chown -R oracle:oinstall /backup/
二、设置定时任务
假设设置定时任务每天下午13:53定时执行.并且会自动删除5天前的数据,
编辑系统任务执行计划crontab -e
53 13 * * * /home/oracle/P_DB_BAK.sh #每天下午13:53,以oracle用户自动执行P_DB_BAK.sh备份文件
#使用绝对路径
[oracle@localhost ~]$ crontab -l
53 13 * * * /home/oracle/P_DB_BAK.sh
查看备份文件:
#我的directory路径为/u01/app/oracle/mydata
[oracle@localhost ~]$ cd /u01/app/oracle/mydata/
[oracle@localhost mydata]$ ll
总用量 828
-rw-r--r-- 1 oracle oinstall 60 9月 12 13:52 :
-rw-r----- 1 oracle oinstall 323584 9月 12 10:45 20230912104408.dmp
-rw-r--r-- 1 oracle oinstall 1558 9月 12 10:45 20230912104408.log
-rw-r----- 1 oracle oinstall 335872 9月 12 10:55 20230912105438.dmp
-rw-r--r-- 1 oracle oinstall 1637 9月 12 10:55 20230912105438.log
-rw-r--r-- 1 oracle oinstall 31634 9月 12 11:05 20230912110454.tar.gz
-rw-r--r-- 1 oracle oinstall 31598 9月 12 11:15 20230912111424.tar.gz
-rw-r--r-- 1 oracle oinstall 31896 9月 12 11:27 20230912112645.tar.gz
-rw-r--r-- 1 oracle oinstall 31920 9月 12 11:29 20230912112901.tar.gz
-rw-r--r-- 1 oracle oinstall 31627 9月 12 13:53 20230912135301.tar.gz
##三、恢复备份
当oracle需要恢复数据时,在/backup文件夹下找到需要备份的数据,使用su - oracle切换
本地备份:
到oracle用户下执行以下命令即可:
impdb 账号/密码DIRECTORY=mydata备份路径 DUMPFILE=full.dmp(根据实际备份文件名情况修改) schemas=用户;
远程备份:
使用imp导入
imp 账户/密码@ip:端口/服务名file=export.dmp fromuser=用户名 touser=用户名;