Anand Sudhanaboina

Backup of Dot Files Using Python & Dropbox

For developers who have 100’s of lines in multiple dot files, backing them up is also important, I’ve seen quite a few developers who copy the files to git or explicitly sync them. This works just fine, but it’s a manual process and duplication of data. I have multiple dot files (shell files, config files, etc) and I wanted a continuous backup solution which need’s zero manual effort.

Update: 2-8-2017

I experimented with Dropbox offical client, which found to be way easier than writing code using Dropbox’s API.

1
2
3
4
5
# Download latest dropbox client and start the client:
wget -O - "https://www.dropbox.com/download?plat=lnx.x86_64" | tar xzf -
cd .dropbox-dist
./dropboxd
# Login to your dropbox folder

After the Dropbox client is up and running, create symbolic links of the directory and file you like to backup, example:

1
2
3
# optional: cd into dropbox folder
ln -s /etc/apache2/sites-enabled/000-default.conf 000-default.conf
ln -s ~/.bashrc .bashrc

Dropbox will backup the actual files / directories to Dropbox.

Outdated

Below is the Python code which uses Dropbox Python API to push files to Dropbox:

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
 #!/usr/bin/env python
import dropbox, logging

# Constants Config:
ACCESS_TOKEN = "[YOUR_DROPBOX_ACCESS_TOKEN]"
LOG_FILE = "/var/www/html/backup-to-dropbox/backup2dropbox.log.txt"

# Login Config:
logging.basicConfig(filename=LOG_FILE,level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger()
logger.info("Starting process!")

# Get dropbox client instance:
client = dropbox.client.DropboxClient(ACCESS_TOKEN)

# File to backup:
files = [{
  "local" : "/home/anand/.zshcrc",
  "remote" : "zshcrc.txt"
},{
  "local" : "/home/anand/.shcommons",
  "remote" : "shcommons.txt"
}]

for file in files:
  logger.info("Uploading: " + file['local'])
  try:
      f = open(file['local'], 'rb')
      response = client.put_file(file['remote'], f, overwrite=True)
      logger.info(response)
  except Exception as e:
      logger.error(e)

Click here - To create a new app and get the Dropbox access token.

When this Python files is executed it will try to push the set of files in files variable and you can see these in Dropbox app folder which you created. local property in files variable is the local file location, remote is the remote file name.

To automate this process, add the cron expression 0 * * * * /use/bin/python dropbox_backup.py in cron tab editor (crontab -e). This will execute the Python script every one hour and pushes the files to Dropbox, however Dropbox client will only update the file in Dropbox if that’s a modified version of the existing file in Dropbox.

Comments