SSH Tricks to Remember

Over the last six months or so, I’ve been connecting via SSH much more than I used to. I’ve learned a few things that I want to remember. Here they are.

Agent ForwardingPermalink

The -A flag is useful if you SSH into a login node and then want to SSH further into the network. When using passwordless authentication via SSH keys, this flag ensures that authentication requests are forwarded so that only the “first” machine in the chain is relevant. Let’s say you connect: laptop --> server1 --> server2 Using the -A flag means that the keys on laptop are used to authenticate on server2, not just server1. The corresponding configuration file option is:

ForwardAgent yes

Adding SSH KeysPermalink

Just because your SSH keys are in ~/.ssh doesn’t necessarily mean they’re added to the authentication agent. At least, they weren’t when I migrated from my Windows machine to my MacBook. Running ssh-add adds the keys to the agent, but they are forgotten after a reboot.

macOS has some special handling for this, which changes from time to time, so checking the latest documentation is a good idea. One alternative is to include:

IdentityFile ~/.ssh/path/to/private/key

in your ~/.ssh/config file. Together with:

AddKeysToAgent yes

this helps work around the issue.

Name ExpansionPermalink

The SSH config file supports wildcards. For example, setting:

Host b*
    HostName foobar-%h

allows the command ssh b100 to expand into ssh foobar-b100. This is very useful when working with multiple machines that have similar names.

What this really does is define a pattern for a set of hostnames. It then modifies the HostName field, replacing %h with the originally specified host. There’s no advanced pattern matching or regex—just simple substitution. Check the TOKEN section in the SSH man page (man ssh_config). The available tokens vary significantly between systems. On my laptop with OpenSSH_9.8p1, they differ greatly from those on my server running OpenSSH_7.4p1.

Local ForwardingPermalink

The -L flag sets up tunnels. For example, when I want to run a Jupyter Notebook on a remote server using port 8080 and TensorBoard on port 6006, I can use:

ssh -L8080:localhost:8080 -L6006:localhost:6006 remote-server

Once the connection is established, opening localhost:8080 in a browser will forward to localhost:8080 on the remote machine. To configure this via the SSH config file, use the LocalForward option.

More OptionsPermalink

To explore all available options for the ~/.ssh/config file, check:

man ssh_config

Updated: