Automatically attaching to a tmux session via SSH

I've been using tmux as a screen replacement for a while now. I find it easier to use and configure than screen. I tend to leave a tmux session running on servers that I administer so that everything is just as it was when I last connected. It's very handy.

To make this even more convenient, I wanted to be able to automatically attach to a running tmux session when connecting to servers using SSH. The SSH client already comes with the ability to run a command when connecting. It works like this:

ssh <hostname> <command>

Unfortunately, this didn't work when I tried attaching to a tmux session.

ssh <hostname> tmux a
not a terminal

After a bit of Googling, it turns out that you need to supply the -t option to the ssh command. The ssh man page describes the option as such:

-t Force pseudo-tty allocation. This can be used to execute
   arbitrary screen-based programs on a remote machine, 
   which can be very useful, e.g., when implementing menu

If we do that, we're in business:

ssh <hostname> -t tmux a

To make the command even shorter, I've been adding bash aliases to my ~/.bash_profile for each server I connect to, like so:

alias servername="ssh servername -t tmux a"

Now, I can just type servername and get a SSH connection to servername with tmux automatically attached. Issuing a <ctrl> + b + d will detach the tmux session and disconnect the SSH connection.

Command line magic!