How to ssh to a remote server without typing your password
Here are a few tips to use
ssh more effectively. Login to your server using
public key encryption instead of typing a password. Use the
file to create short and memorable aliases for your servers. Also, use aliases
to connect through a login server into a work server.
1. Generate and install a key pair#
On your laptop, generate a new key pair:
#!/usr/bin/env bash # Create this folder if it does not exist, and set the correct permissions. mkdir -p ~/.ssh && chmod 700 ~/.ssh # Generate an RSA key pair for identification with the remote server. # You may accept all the default settings by pressing Enter. ssh-keygen -t rsa
ssh-keygen will create two files:
~/.ssh/id_rsais the private key. Never share this with anyone.
~/.ssh/id_rsa.pubis the public key. This can be shared with everyone.
Now we can install the public key on the remote server:
# Your remote username, an @ sign, and the hostname of your remote server. firstname.lastname@example.org' # Set correct permissions on the remote server, or else ssh will not work. ssh $host 'chmod g-w,o-w ~; mkdir -p ~/.ssh; chmod 700 ~/.ssh' # Copy your public key to the remote server cat ~/.ssh/id_rsa.pub | ssh $host 'cat >> ~/.ssh/authorized_keys; chmod 600 ~/.ssh/authorized_keys'
At this point, you should be able to connect to your server without typing a password:
2. Use an alias for your server's address#
You might prefer to type something memorable like
jupiter (7 characters)
email@example.com (21 characters). To create an alias for
your server, make a config file
~/.ssh/config on your laptop as shown below.
You'll be able to use the
jupiter alias with
# ~/.ssh/config Host jupiter User carl HostName myserver.com
At this point, you should be able to connect to your server like this:
3. Automatically connect to a work server through a login server#
If you want a single command to do two steps:
- Connect to a login server
- Once connected to
jupiter, connect to a work server
Then configure your
~/.ssh/config file as follows:
# ~/.ssh/config Host jupiter User carl Hostname myserver.com Host saturn User carl ProxyCommand ssh -qX jupiter nc %h %p
At this point, you should be able to connect to
How to write your own config file:
All available configuration options: