Thursday, March 24, 2011

Dynamic IP + Dropbox = consistent SSH connection

So you want to be able to Secure Shell into your home computer, but you have a dynamic IP address. As long as you've got access to a Dropbox account and *nix computer on your home network with an Airport router, this solution should work for you. The basic idea is to have a script that updates your SSH config file nightly with your router's IP address while keeping the SSH config file synced via Dropbox. 


Set up Dropbox
The first step is to move your ~/.ssh/config file to your Dropbox directory (you have Dropbox, right?) and set up a symbolic link to replace the old file.


mkdir -p ~/Dropbox/dotfiles/.ssh
mv ~/.ssh/config ~/Dropbox/dotfiles/.ssh
ln -s ~/Dropbox/dotfiles/.ssh/config ~/.ssh/config


(Note: If you have multiple Mac and *nix-based computers I recommend this method for keeping your .profile files in sync as well)


Set up a script to get your IP address


I found this script from Mac OS X Hints that will get the IP of your Airport router (I haven't tested it on any other routers so your mileage may vary). I also tweaked it to update the ~/.ssh/config file with the latest IP. It assumes your config file is of a similar style (Note: this only works if you have one Host with an IP address for a HostName. I'd love any help with updating the script.):
Host home
  HostName 123.456.789.12
  User username
  Port 11234

Here's the script to update get your current public IP address and update your ~/.ssh/config file (just update the HOMEPATH to point to your home directory). I called it ~/update_ip.sh

Set up a nightly update


Finally set up the script to run every night.  I opted for a basic cron job. That way if you're gone for a week and your IP changes, you can still SSH into your home. Even if you don't have another device setup to sync with your Dropbox, you can still log into your account via the web interface to check out the your most current IP address by reading the config file.


First create the crontab that will run nightly at 3 AM, or whenever works best for you, by calling
crontab -e
and entering (with your username)


0        3        *       *          *       username     sh /Users/username/update_ip.sh
And that should be it. You should now be able to ssh home any time you want, even when your router's IP changes.