When we talk about SSH, we are usually referring to OpenSSH - a FREE version of the SSH connectivity tools. As their official website said:

OpenSSH encrypts all traffic (including passwords) to effectively eliminate eavesdropping, connection hijacking, and other attacks. Additionally, OpenSSH provides secure tunneling capabilities and several authentication methods, and supports all SSH protocol versions.

And I believe ssh is one of the most used commands for programmers (Windows users, you have putty, that’s … not bad). In this post I am going to list some most basic usage of ssh.

How to generate key pair?

They are two ways to identify users: via password and via key pair. The latter one is more secure. We can generate a key pair through:

$ ssh-keygen -t rsa -C "[email protected]"
# Creates a new ssh key, using the provided email as a label
Generating public/private rsa key pair.
# Enter file in which to save the key (/Users/you/.ssh/id_rsa): [Press enter]

where -t stands for encryption type, -C for comment. Then choose a strong passphrase (in case of your rsa keys being stolen). Now, you will see id_rsa (private key) and id_rsa.pub (public key)in your ~/.ssh/ directory(Don’t let others know your private key).
At last, add your key to ssh-agent(a keys management tool):

eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa

How to SSH login without authentication?

Now it’s time use our public key. For Linux user:

ssh-copy-id user@machine

For Mac user, we can either brew install ssh-copy-id to install and use this command or typing:

cat ~/.ssh/id_rsa.pub | ssh user@machine "mkdir ~/.ssh; cat >> ~/.ssh/authorized_keys"

As you can tell, actually what we are doing here is copy the content of id_rsa.pub to server’s ~/.ssh/authorized_keys.

Make an alias of the connection

Laziness is a great virtue of a programmer. Add these to local ~/.ssh/config (create if not exist) to simplify your life:

Host matrix
     HostName <domain name or public IP>
     User <user name>
     IdentityFile </path/to/private_key>

One more thing, ssh config support wildcard, so you can use

Host *compute-1.amazonaws.com

for all your ec2 instances. I also added

TCPKeepAlive=yes
ServerAliveInterval=15    
ServerAliveCountMax=6
StrictHostKeyChecking=no
Compression=yes
ForwardAgent=yes
RSAAuthentication=yes
PasswordAuthentication=yes

in my config file to add more feature.

About security

  1. Always set passphrase, or it might be stolen from memory.
  2. Maybe, use another port instead of 22 is a good idea (Check this: Changing your ssh server’s port from the default: Is it worth it?)