Sam Hooke

SSH tips

Following are some tips to help remind myself how to perform SSH tasks that I do less frequently.

Passwordless SSH login §

Passwordless SSH login is when you run ssh user@server, and are automatically logged in without being prompted for a password.

There are essentially just two steps for setting up passwordless SSH login:

  1. Generate a key.
  2. Install the key on the relevant server(s).

Generate the key §

Simply run:

ssh-keygen

When prompted for a passphrase, just press enter.

If you do enter a passphrase, you will be prompted for that passphrase when you try to log in to a server with your key.

Install the key (automatically) §

Simply run:

ssh-copy-id user@server

This will install your key to the specified server. You will be prompted for a password (but hopefully this will be the last time!).

Install the key (manually) §

On some systems, the ssh-copy-id script may not exist. For example, on Windows 10. Fortunately, the script itself is fairly simple, so you can manually perform it by doing the following:

# Use scp to copy your public key to the target server
scp ~/.ssh/id_rsa.pub user@server:my_id_rsa.pub

# Log in to the target server
ssh user@server

# Append your public key to the authorized keys
cat my_id_rsa.pub >> ~/.ssh/authorized_keys

Install the key (manually, via Cygwin) §

Same as above, but if using Cygwin it may be necessary to use quotes to handle the Windows path, e.g.:

scp "C:\Users\sam/.ssh/id_rsa" user@server:my_id_rsa.pub

Install the key (manually, on a different port) §

Same as above, but if not using port 22, you can specify the port using the -P option:

scp -P 12345 ~/.ssh/id_rsa.pub user@server:my_id_rsa.pub

Note that the position of -P is important. It must come before the file argument else a No such file or directory error will occur as the port is misinterpreted as an additional file:

scp ~/.ssh/id_rsa.pub user@server:my_id_rsa.pub -P 12345
12345: No such file or directory

Similarly, don’t let your ssh muscle memory trick you! Using -p (rather than -P) actually means “preserve modification times, access times, and modes”. As such, the command is valid, but won’t do what you want:

scp -p 12345 ~/.ssh/id_rsa.pub user@server:my_id_rsa.pub
ssh: connect to host server port 22: Connection refused
lost connection

SSH tunneling §

Can SSH tunnel through a gateway:

ssh -L local_port:target_ip:target_port user@gateway_ip

Can do SSH tunnels to multiple ports/hosts in one go:

ssh -L local_port_a:target_ip_a:target_port_a -L local_port_b:target_ip_b:target_port_b user@gateway_ip

These are rough notes that vary greatly in quality and length, but prove useful to me, and hopefully to you too!

← Previous: mypy and verbose logging
Next: mypy tips →