Created
July 12, 2010 18:35
-
-
Save jwood/472874 to your computer and use it in GitHub Desktop.
A simple backup script that FTPs files to some safe place
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) | |
ftp.rename(from_filename, to_filename) | |
rescue | |
# Swallow - who cares | |
end | |
# | |
# Delete the file, if it exists | |
# | |
def delete_if_exists(ftp, file_to_delete) | |
ftp.delete(file_to_delete) | |
rescue | |
# Swallow - who cares | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment