點燈坊

失くすものさえない今が強くなるチャンスよ

Setting Up SSH Keys on Ubuntu

Sam Xiao's Avatar 2021-11-23

We can login to Ubuntu without any password by storing the private key on the local machine and the public key on the remote server.

Version

Ubuntu 21.10

ssh-keygen

$ ssh-keygen -t rsa -b 4096 -C "oomusou"

Generate SSH private key and public key.

  • -t rsa : specify RSA2 protocol to generate key
  • -b 4096 : specify 4096 bits to generate key
  • -C : specify login name of Ubuntu

ssh000

  • if id_rsa exists, enter another name for the new ssh key
  • Leave empty for passphrase

ssh-copy-id

$ ssh-copy-id -i ./id_rsa_ubuntu oomusou@ubuntu-test

Copy public key to Ubuntu.

  • -i : specify the location of the SSH key
  • oomusou@ubuntu-test : username@server

ssh001

Number of key(s) added: 1 means ssh-copy-id copies the public key to the server successfully.

SSH Config

# GitHub
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa

# Ubuntu
Host ubuntu
HostName ubuntu-test
User oomusou
IdentityFile ~/.ssh/id_rsa_ubuntu

We often have multiple SSH keys on the local machine; for example, we already have an SSH key for GitHub, but we want to add a different SSH key for Ubuntu.

We have to edit the config file in the .ssh directory to manage multiple SSH keys.

Line 7

# Ubuntu
Host ubuntu
HostName ubuntu-test
User oomusou
IdentityFile ~/.ssh/id_rsa_ubuntu

Add new section for Ubuntu :

  • Host : nickname for server
  • HostName : actual hostname for the server
  • User : login user name
  • IdentityFile : the location of SSH private key file

ssh

$ ssh oomusou@ubuntu

Use ssh to login to Ubuntu without any password.

ssh002

Conclusion

  • If we don’t have any other SSH key on the local machine, we don’t need to edit the config file in the .ssh directory

Reference

Linuxize, How to Set Up SSH Keys on Ubuntu 20.04