Created
March 18, 2018 14:52
-
-
Save lkdjiin/a782da2f911cbf802c1e29245ff63cb3 to your computer and use it in GitHub Desktop.
Backup postgresql using a ftp server
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/env ruby | |
require 'net/ftp' | |
SERVER = "" | |
LOGIN = "" | |
PASSWORD = "" | |
# First, dump the database. | |
filename = "database-#{Time.now.strftime("%Y-%m-%d-%H")}.sql" | |
command = "pg_dump 'postgres://user:password@server:port/db' > #{filename}" | |
result = system(command) | |
# Then save the dump over ftp. | |
Net::FTP.open(SERVER, LOGIN, PASSWORD) do |ftp| | |
ftp.putbinaryfile(File.new(filename)) | |
end | |
# Keep 10 backups on the backup server. | |
Net::FTP.open(SERVER, LOGIN, PASSWORD) do |ftp| | |
files = ftp.nlst | |
files.pop(10) | |
files.each { |f| ftp.delete(f) } | |
end | |
# Keep 3 backups locally. | |
files = Dir.glob("database-*") | |
files.sort! | |
files.pop(3) | |
File.unlink(*files) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment