Skip to content

Instantly share code, notes, and snippets.

@Grace
Last active August 13, 2023 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Grace/4e10852e275078e746af to your computer and use it in GitHub Desktop.
Save Grace/4e10852e275078e746af to your computer and use it in GitHub Desktop.
A bash script to backup your SSH keys to Dropbox
#!/bin/bash
# Purpose: This is a script to backup your SSH folder to
# your local Dropbox folder, therefore syncing it to your Dropbox.
# Author: Grace Christenbery
# Use case: You can run this as a cron job to
# backup your SSH keys once per day to Dropbox! Awesome!
# Security Disclaimer:
# You'll want to make sure your keys are secure in Dropbox.
# Always password protect your SSH keys when you generate them, and also enable
# two-factor authentication for your Dropbox: https://www.dropbox.com/en/help/363#enable.
# Your local SSH directory
SSH_DIR="$HOME/.ssh/"
# Your directory to save to in your local Dropbox directory
DROPBOX_TARGET_DIR="$HOME/Dropbox/backups/ssh/"
# Your username on your computer (not your Dropbox username)
USER=$(whoami)
# The file name for our backup that we're making.
BACKUP_NAME=$USER-ssh-$(date +%Y%m%d)
# Print out the purpose of our script to the console
echo "Backing up your SSH directory to your Dropbox."
# If the directory ~/Dropbox/backups/ssh/ exists, we want to
# save our ssh keys there. So, if ~/Dropbox/backups/ssh/ is
# present on the computer, tar up the ~/.ssh/ folder and
# save it there. If it isn't present, we create the
# directory and tar up our ~/.ssh/ folder anyway.
# The -p switch makes the directory if it isn't present! :-)
mkdir -p $DROPBOX_TARGET_DIR
# Ensure the directory ~/.ssh/ exists before we tar it. If it doesn't exist,
# we probably don't have any ssh keys we want to back up on the computer,
# so we don't do anything in that case.
# The -f switch tells the command the directory name to write to.
# The -c switch tells the command to write to the directory given.
# The -k switch makes sure that the backup created doesn't
# overwrite any existing files.
# The -Z switch tells tar to compress the backup we create.
# The -P switch uses absolute file names. It's not important other than
# for avoiding the unneeded tar output message, "tar: Removing leading
# '/' from member names", when you run this script.
if [ -d $SSH_DIR ]; then
BACKUP=$BACKUP_NAME.tgz
sudo tar -PkcZf $DROPBOX_TARGET_DIR$BACKUP $SSH_DIR >/dev/null
echo "Backup complete."
else
echo "Error: Hmm, you don't have an SSH folder to backup to Dropbox."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment