Backup pfsense (via SSH) using ONE script



  • I've finally gotten around to writing a Python Fabric script that logs into my pfsense instances via SSH, generates a backup and pulls that back via SFTP.

    
    #!/usr/bin/python
    #
    # Designed and tested on pfsense v2.2
    #
    import urllib2, base64, getpass, json, re, sys, os
    from fabric.api import *
    from datetime import datetime
    #
    myname = ('root')
    # NOTE: pfsense uses root user that has same password as admin - required for sftp file access
    theList = ['pfsense1.company.com','pfsense2.company.com']
    #
    i = datetime.now()
    now_is = i.strftime('%Y%m%d-%H%M%S')
    today_is = i.strftime('%Y%m%d')
    print now_is
    #
    print ('')
    print ('Username is ' + myname)
    pw = getpass.getpass()
    print ('')
    #
    how_many = len(theList)
    #
    print("This will backup " + str(how_many) + " systems:\n")
    print (theList)
    print ('')
    #
    env.user = myname
    env.hosts = theList
    env.password = pw
    #
    #@parallel(pool_size=5)
    #
    # generate the backup file on the pfsense system itself, this will take some time
    def generate_and_pull_backup():
            env.warn_only = True
    #       run( "8", shell=False )
            backup_command_output = run( "/etc/rc.create_full_backup", shell=False )
    # parse the output of the create_full_backup command
            file_generated_full_path = backup_command_output.rsplit(None, 1)[-1]
            filename_generated = file_generated_full_path.split('/')[-1]
    # pull the backup home to me
            get("%s" % file_generated_full_path,"./my_pfsense_backups/%s/%s-%s" % (today_is,env.host,filename_generated))
    # NOTE: configs can be restored via /etc/rc.restore_full_backup
    #
    # delete config backup just generated so disk does not fill
            run( "rm -f %s" % file_generated_full_path, shell=False )
    #
    if __name__ == '__main__':
            execute(generate_and_pull_backup)
    
    

    For more info you can view my blog that has other Fabric examples: http://paklids.blogspot.com/2015/09/backup-pfsense-firewall-via-ssh-using.html

    Oh, and be sure to enable secure shell in System>Advanced on all the pfsense systems that you would like to connect to.