Skip to content

Instantly share code, notes, and snippets.

@lkdjiin
Created March 18, 2018 14:52
Show Gist options
  • Save lkdjiin/a782da2f911cbf802c1e29245ff63cb3 to your computer and use it in GitHub Desktop.
Save lkdjiin/a782da2f911cbf802c1e29245ff63cb3 to your computer and use it in GitHub Desktop.
Backup postgresql using a ftp server
#!/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