Welcome, guest | Sign In | My Account | Store | Cart

UPDATE: This is script is not maintained and does not anymore with the current version of Dropbox. For a proper command line interface to dropbox I recommend dropbox_uploader: https://github.com/andreafabrizi/Dropbox-Uploader

Originally inspired by the example at http://joncraton.org/blog/62/uploading-dropbox-python.

The script uses mechanize to logon to the web page and upload the file(s) to the Dropbox root folder or to the folder supplied on the command line as dir:/my_dropbox_path (if present, this must be the first parameter).

Multiple files and/or glob patterns names are accepted as script arguments.

Example usage
dropbox.py file1.txt                       # upload to root folder
dropbox.py dir:/Backups/2012 file1.txt     # upload to custom folder
dropbox.py dir:/Backups/2012 *.txt         # upload by file mask
dropbox.py dir:/Backups/2020 *             # upload all files in current dir

Limitations: only files in current folder are processed, subfolders are ignored.

NOTE

The script requires the mechanize module - use pip install mechanize or easy_install mechanize to add it to your site-packages.

NOTE2

I have found a cleaner way to manage dropbox files from the console - see the dropbox-uploader script at https://github.com/andreafabrizi/Dropbox-Uploader - it is a Bash script that works using the official Dropbox API rather than emulating a web browser.

Python, 124 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import mechanize
import os
import glob

verbose = True

def usage():
    print '''
Upload file(s) to dropbox.
    dropbox.py file1.txt                       # upload to root folder
    dropbox.py dir:/Backups/2012 file1.txt     # upload to custom folder
    dropbox.py dir:/Backups/2012 *.txt         # upload by file mask
    dropbox.py dir:/Backups/2020 *             # upload all files in current dir
'''

def upload_files(local_files, remote_dir, email, password):
    """ Upload a local file to Dropbox """

    # Fire up a browser using mechanize
    br = mechanize.Browser()

    br.set_handle_equiv(True)
#    br.set_handle_gzip(True)
    br.set_handle_redirect(True)
    br.set_handle_referer(True)
    br.set_handle_robots(False)

#    br.set_debug_http(True)
#    br.set_debug_responses(True)
#    br.set_debug_redirects(True)

    br.addheaders = [('User-agent', ' Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1018.0 Safari/535.19')]

    if verbose: print 'Opening login page...'
    # Browse to the login page
    r = br.open('https://www.dropbox.com/login')
    # just in case you need the html
    # html = r.read()
    # this shows a lot of info

    print r.info()

    if verbose: print br.title(), br.geturl()

    # Enter the username and password into the login form
    isLoginForm = lambda l: l.action == "https://www.dropbox.com/login" and l.method == "POST"

    try:
        if verbose: print 'selecting form...'
        br.select_form(predicate=isLoginForm)
    except:
        print("Unable to find login form.");
        exit(1);

    br['login_email'] = email
    br['login_password'] = password

    # Send the form
    if verbose: print 'submitting login form...'
    response = br.submit()

    # Add our file upload to the upload form once logged in
    isUploadForm = lambda u: u.action == "https://dl-web.dropbox.com/upload" and u.method == "POST"

    for local_file in local_files:
        try:
            br.select_form(predicate=isUploadForm)
        except:
            print("Unable to find upload form.");
            print("Make sure that your login information is correct.");
            exit(1);
            
        br.form.find_control("dest").readonly = False
        br.form.set_value(remote_dir, "dest")

        remote_file = os.path.basename(local_file)
        
        if (os.path.isfile(local_file)):
            br.form.add_file(open(local_file, "rb"), "", remote_file)
            # Submit the form with the file
            if verbose: print 'Uploading %s... to <<Dropbox>>:/%s/%s' % (local_file, remote_dir, remote_file),
            br.submit()
        
            if verbose: print 'Ok'
                
    print 'All completed Ok!'
    
if __name__ == "__main__":
    import sys
    from getpass import getpass
    email = raw_input("Enter Dropbox email address:")
    password = getpass("Enter Dropbox password:")
    # email = ''
    # password = ''

    # allow multiple local file names as input args
    # first arg with 'dir:' prefix is parsed as remote path
    if len(sys.argv) > 1:
        if sys.argv[1].lower().startswith('dir:'):
            remote_dir = sys.argv[1][4:]
            
            if not remote_dir.startswith('/'):
                remote_dir = '/' + remote_dir
                
            if verbose: print 'Using remote_dir=', remote_dir
            del sys.argv[1]
        local_files = sys.argv[1:]

    prepared_local_files = []
    
    for local_file in local_files:
        
        # explode globs
        if '*' in local_file:
            prepared_local_files += glob.glob(local_file)
        else:
            prepared_local_files.append(local_file)

            
    if not len(prepared_local_files):
        usage()
        sys.exit(2)

    upload_files(prepared_local_files, remote_dir, email, password)

1 comment

Duc 12 years, 2 months ago  # | flag

wow, very nice scripts