Josh Dick portrait Josh Dick

SSH via iCloud

Easily SSH between Macs associated with your iCloud account.

I recently happened upon a great tip from One Thing Well that explained that it is possible to SSH between Macs via iCloud, provided that the client and target computers are signed into the same iCloud account, and that the target computer has Back To My Mac enabled in iCloud System Preferences.

I’ll start with some background information that I gleaned from the One Thing Well post.

You can SSH between iCloud-connected machines thusly:

ssh [computer name].[account number].members.btmm.icloud.com

where:

  • [computer name] is the output of: $ scutil –get ComputerName
  • [account number] can be found (in the last line of the output) by running: $ dns-sd -E or alternatively, by running: $ echo show Setup:/Network/BackToMyMac | scutil | sed -n ’s/.* : (.).$/\1/p'

Rather than trying to remember all of that information, I decided to write a handy shell function to make things easier:

# On Mac OS X, SSH to another Mac by hostname via Back To My Mac (iCloud)
# The client and target machines must both have Back To My Mac enabled
# Adapted from code found at <http://onethingwell.org/post/27835796928/remote-ssh-bact-to-my-mac>
function sshicloud() {
  if [[ $# -eq 0 || $# -gt 2 ]]; then
    echo "Usage: $0 computername [username]"
  elif ! hash "scutil" &> /dev/null; then
    echo "$0 only works on Mac OS X! Aborting."
  else
    local _icloud_addr=`echo show Setup:/Network/BackToMyMac | scutil | sed -n 's/.* : *\(.*\).$/\1/p'`
    local _username=`whoami`
    if [[ $# -eq 2 ]]; then
      _username=$2
    fi
    ssh $_username@$1.$_icloud_addr
  fi
}

I’ve tested this shell function in both zsh and bash. You can simply paste it into your ~/.zshrc or ~/.bashrc file.

If you have two Macs named ‘cheech’ and ‘chong’ that are both signed into the same iCloud account, have Back To My Mac enabled, and have the same user account name (“short name”), this sshicloud shell function allows you to SSH between them by invoking sshicloud cheech and sshicloud chong. If you want to specify a different account name, simply put it after the computer name: sshicloud cheech anotheruser.

I’ve found that SSH via iCloud even works in situations where I would have otherwise had to open a VPN connection in order to SSH to the target computer; the target computer’s SSH port doesn’t have to be forwarded/exposed from inside its network. Handy!

[ ↩ all writing posts ]