My Python FTP Deploy Script

I schedule all my scripts to run on a WebFaction server. That gives me excellent up time, and the ability to install my own programs and python libraries. So far they have proved to be a kick-ass web hosting service.

I needed a way to push code updates to my scripts up to the server and so I quickly put together a simple script that uses FTP to transfer the files I need uploaded.

It’s not very sophisticated and there are probably better ways to deploy code such as using mercurial, or rsync to push out updates without stepping on remote code changes. But the FTP approach will work just fine.

This script uses a hard-coded list of files that I want to always push to the server.

here it is:

#!/usr/bin/env python
import ftplib
 
USERNAME='username'
PASSWORD='password'
HOST = 'ftp.server.com'
REMOTE_DIR = './bin/'
info= (USERNAME, PASSWORD)
 
files = ('file1.py', 'file2.py')
 
def connect(site, dir, user=(), verbose=True):
    if verbose:
        print 'Connecting', site
    remote = ftplib.FTP(site)   
    remote.login(*user)
    if verbose:
        print 'Changing directory', dir
    remote.cwd(dir)
    return remote
 
def putfile(remote, file, verbose=True):
    if verbose: 
        print 'Uploading', file
    local = open(file, 'rb')    
    remote.storbinary('STOR ' + file, local, 1024)
    local.close()
    if verbose: 
        print 'Upload done.'
 
def disconnect(remote):
    remote.quit()
 
if __name__ == '__main__':
    remote = connect(HOST, REMOTE_DIR, info)
    for file in files:
        putfile(remote, file)
    disconnect(remote)