Pages

Saturday, March 24, 2012

Easy Windows Batch File Backups (with MySQL, MsSQL, and email notifications included)

I scheduled a .bat file with this script in it for each site I host and it drops everything into a single file for me per the schedule frequency.  I’m even free to email myself or clients their entire application source.

Prerequsites for this script to work are Winrar (not the free version, but a purchased version as I don’t think the free versions allow command line interfaces through rar.exe) and SendEmail (free).  I’ve separated the code a bit so you should be able to customize the top portion with your paths, etc. 


@ECHO off
 
REM *** CONFIGURE HERE (Leave mysql or mssql blank to skip database backup) ***
 
SET rootdir=\Inetpub\yourdomain.com
SET siteName=YourDomain.com
SET backupFolder=WWW
 
SET mysql=database_name
SET mssql=database_name
 
SET mysqlServer=localhost
SET mysqlPass=password
SET mssqlServerInstance=localhost\instanceName
 
SET WinRarexeLocation=C:\progra~1\WinRAR\rar
SET sendMailexeLocation=C:\folder_name\sendEmail.exe
 
SET emailFromAddress="auto_backups@yourdomain.com"
SET emailToAddress="steve@yourdomain.com"
SET smtpServer=smtp.yourdomain.com:25
 
REM *** Careful editing below this ********************************************
 
cd\
cd%rootdir%
 
REM *** Backup MySQL and/or MsSQL databases if db names specified ***
if defined mysql mysqldump -h %mysqlServer% -u root -p %mysql% > db_backup.sql --password=%mysqlPass%
if defined mssql sqlcmd -S "%mssqlServerInstance%" -Q "BACKUP DATABASE %mssql% TO DISK = 'C:%rootdir%\%mssql%_db.bak';"
 
REM *** Save contents of specified directory to .rar archive ***
%WinRarexeLocation% a -agMM_DD_YYYY_HHMMSS BAK .rar %backupFolderr% db_backup.sql %mssql%_db.bak
 
del db_backup.sql
del %mssql%_db.bak
 
set myDir1=C:%rootdir%\*.rar
set fileinfo=
 
for /f "delims=" %%a in ('dir /b /a-d %myDir1% 2^>NUL') do call :process %%a %%~zna
%sendMailexeLocation% -f %emailFromAddress% -t %emailToAddress -u "%siteName% Backed Up!" -s %smtpServer% -m "All source and/or database files for %siteName% have been backed up.\n\nBackup files available are:\n\nNAME                                   FILE SIZE\n-------------------------------------------------------------\n%fileinfo%\n\nEnjoy!"
 
:process
if not "%fileinfo%"=="" set fileinfo=%fileinfo%\n
set fileinfo=%fileinfo%%~1   %~2


I put all website source code into a WWW for each site – so that’s why I added a backupFolder variable to the script.  You can list as many other files or folders (separated by a space) or use *.* to include all files in the specified folder.

No comments:

Post a Comment