以下腳本執行 SQL Server 中某一數據庫全備份,並將備份文件傳至另一機器。備份文件命名規則:數據庫名_時間戳.BAK。
執行環境: windows 2003 server SQL Server 2000
@ECHO off
REM Backup Database Script Log Files
SET dbbak_dir=e:testdbbak
if not exist %dbbak_dir% mkdir %dbbak_dir%
REM Backup Database Name
SET B_Database_Name=db1
SET B_DATE=%date:~0,4%%date:~5,2%%date:~8,2%
ECHO use master ;>%dbbak_dir%FULL_backup.sql
ECHO go >>%dbbak_dir%FULL_backup.sql
rem ECHO SP_ADDUMPDEVICE 'DISK',>>%dbbak_dir%FULL_backup.sql
rem ECHO '%B_Database_Name%_%B_DATE%_FULL', >>%dbbak_dir%FULL_backup.sql
rem ECHO '%dbbak_dir%%B_Database_Name%_%B_DATE%_FULL.bak'; >>%dbbak_dir%FULL_backup.sql
rem ECHO go >>%dbbak_dir%FULL_backup.sql
ECHO BACKUP DATABASE %B_Database_Name% >>%dbbak_dir%FULL_backup.sql
ECHO TO DISK = '%dbbak_dir%%B_Database_Name%_%B_DATE%_FULL.bak' >>%dbbak_dir%FULL_backup.sql
ECHO WITH INIT , NOUNLOAD ;>>%dbbak_dir%FULL_backup.sql
ECHO go >>%dbbak_dir%FULL_backup.sql
ECHO .
REM osql.exe path
SET OSQL_PATH=C:Program FilesMicrosoft SQL Server80ToolsBinn
REM Database user name and password
SET DBUser=sa
SET DBpassword=passwd
ECHO BACKUP DATABASE
"%OSQL_PATH%osql.exe" -U %DBUser% -P %DBpassword% -i %dbbak_dir%FULL_backup.sql -o %dbbak_dir%%B_Database_Name%_%B_DATE%_FULL.log
REM FTP info
set FTP_User=user1
set FTP_PW=passwd
set FTP_IP=10.1.9.1
set FTP_PORT=21
set FTP_DIR=/home/dbbak
SET NCFTP_PATH=D:Program FilesNcFTP
"%NCFTP_PATH%ncftpput.exe" -u %FTP_User% -p %FTP_PW% -P %FTP_PORT% %FTP_IP% %FTP_DIR% %dbbak_dir%%B_Database_Name%_%B_DATE%_FULL.*
REM Delete old backup files
FORFILES /P %dbbak_dir% /D -7 -M %B_Database_Name%*.bak /C "cmd /c del @file"
FORFILES /P %dbbak_dir% /D -7 -M %B_Database_Name%*.log /C "cmd /c del @file"
REM Delete Temp files
DEL /Q %dbbak_dir%FULL_backup.sql
說明:
1. 為避免 Windows 自帶 FTP Client 的 PORT、PASV問題,使用 ncftp client
2. 保留最新 7 天的備份,使用 Resource kit 裡的命令 FORFILES 刪除老備份文件
3. ftp 目的機器是一個 linux 系統,用下面的 shell 腳本刪除老備份文件
#!/bin/sh
cd /home/dbbak/
if [[ -s mm_db_`date +%Y%m%d`*.BAK ]]
then
#echo "not 0"
find . -mtime +7 | xargs rm
fi