Skip to content

Instantly share code, notes, and snippets.

@andreydjason
Created May 16, 2012 16:36
Show Gist options
  • Save andreydjason/2711990 to your computer and use it in GitHub Desktop.
Save andreydjason/2711990 to your computer and use it in GitHub Desktop.
Examples of using RSYNC to do Backups of local to remote, and send result by email (Ruby)
#!/home/andrey/.rvm/bin/ruby-1.9.2-p290
Dir.chdir("/home/andrey/rails_apps/")
def make_backup_of_app(app_name, *destinations)
date_name = Time.now.localtime.strftime("%y.%m.%d_%H%M")
file_name = "#{app_name}_#{date_name}.tar.gz"
if destinations.is_a?(Array)
destinations.each do |destination|
%x(tar -cvzpf #{destination}#{file_name} #{app_name})
end
else
%x(tar -cvzpf #{destination}#{file_name} #{app_name})
end
end
make_backup_of_app('APP_NAME_HERE', '/home/andrey/Dropbox/WHATHEVER_FOLDER_YOU_WANT/', '/home/andrey/HIVE/ANOTHER_WHATHEVER_FOLDER_YOU_WANT/')
require 'date'
require 'time'
require 'net/smtp'
Dir.chdir('/home/andrey/Cronjobs/')
def verify_rsync_output(rsync_output)
if rsync_output == ''
raise RuntimeError, '* Rsync returned empty result for backup - SSH access to the server has ben set?'
end
end
today = DateTime.now
subject_date = today.strftime("%Y%m%d")
full_date = today.strftime("%A, %d/%B/%Y at %H:%M")
server_backup_command = "rsync -aHxvz --delete --numeric-ids -e \"ssh -c arcfour -x -i /home/andrey/.ssh/id_rsa\" /home/andrey/HIVE/WHATEVER_FOLDER/ [email protected]:/home/html/.andrey/HIVE/WHATEVER_FOLDER/"
begin
output = ''
output << "--- Data/Hora: " << full_date << "\n\n"
output << "--- [Backup de '/home/andrey/HIVE/WHATEVER_FOLDER/']\n"
rsync_output = %x[#{server_backup_command}]
output << rsync_output
verify_rsync_output(rsync_output)
output << "\n//------------------------------------------------------------------------------//\n\n"
output << "--- [Backup de '/home/andrey/HIVE/BACKUP/WHATEVER_FOLDER/']\n"
rsync_output = %x[#{server_backup_command}]
output << rsync_output
output << "\n//------------------------------------------------------------------------------//"
verify_rsync_output(rsync_output)
rescue RuntimeError => thisError
error_output = thisError
end
# Send E-mail about the Backup
email_backup_content = (error_output.nil?) ? output : error_output
message = <<MESSAGE
From: ME <[email protected]>
To: My Name <[email protected]>
Subject: Backup Geral HIVE [#{subject_date}]
#{email_backup_content}
MESSAGE
Net::SMTP.start('mail.agenciahive.com.br', 25, 'localhost', '[email protected]', 'password', :plain) do |smtp|
smtp.send_message message, '[email protected]', ['[email protected]']
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment