Backup Script
October 14th, 2008
A convenient little script that will backup a file to a remote server. The script, as it appears below, will keep the 7 most recent versions of the backup around on the remote server. After that, the oldest one is removed before the new one is placed on the server.
The script
#!/usr/bin/ruby
#
# Usage: ftp-backup.rb <directory> <filename>
# Example: ftp-backup.rb /home/jwood/backup/ my_important_file
require 'net/ftp'
NUM_BACKUPS = 7
directory_name = ARGV[0]
file_name = ARGV[1]
server = 'my.server.address'
username = 'jwood'
password = 'secret'
remote_dir = 'backup'
#
# Rename the file to the new name, if it exists
#
def rename_if_exists(ftp, from_filename, to_filename)
begin
ftp.rename(from_filename, to_filename)
rescue
# Swallow - who cares
end
end
#
# Delete the file, if it exists
#
def delete_if_exists(ftp, file_to_delete)
begin
ftp.delete(file_to_delete)
rescue
# Swallow - who cares
end
end
#
# Coordinate the backup
#
Net::FTP.open(server) do |ftp|
ftp.login(username, password)
ftp.chdir(remote_dir)
delete_if_exists(ftp, "#{file_name}.#{NUM_BACKUPS-1}")
(NUM_BACKUPS-2).downto(1) do |i|
rename_if_exists(ftp, "#{file_name}.#{i}", "#{file_name}.#{i+1}")
end
rename_if_exists(ftp, file_name, "#{file_name}.1")
ftp.putbinaryfile(directory_name + file_name)
end