Skip to content

SSH keys and ~/.ssh/config

AdvancedLesson 48 of 669 min

Log in with a key instead of a password: make one with ssh-keygen, install it with ssh-copy-id, keep it private and name servers in ~/.ssh/config.

Typing a password for every ssh gets old fast, and passwords can be guessed. A key pair is better: two matching files made on your laptop. The private key never leaves it. The public key goes on every server you want to reach. When you connect, the server checks you have the private half, and no password crosses the network. The machines here (your laptop, web, db and the router) are pretend ones inside your browser, so nothing you type reaches a real network.

Make a key

ssh-keygen -t ed25519 -C "learner laptop"

-t ed25519 picks a modern key type, -C adds a label. It asks where to save the key (the default, ~/.ssh/id_ed25519, is right) and for a passphrase, which locks the private key on disk. A real key deserves one; here the practice shell presses Enter for you.

ls -l ~/.ssh

id_ed25519 is the private key, readable only by you (-rw-------). id_ed25519.pub is the public one, safe to share.

Careful:ssh ignores a private key that other people can read, and says so ("UNPROTECTED PRIVATE KEY FILE"). Keep it at 600: chmod 600 ~/.ssh/id_ed25519.

Put it on the server

ssh-copy-id web logs in once with your password and adds your public key to ~/.ssh/authorized_keys on web. From then on, ssh web uses the key.

Short names: ~/.ssh/config

~/.ssh/config is a file of settings per server. A Host block gives a server a short name, and the lines under it say where it really is:

Host shop
    HostName web
    User learner
    IdentityFile ~/.ssh/id_ed25519

Now ssh shop means "ssh as learner to web with this key", and scp understands it too. Port sets a different port. Write the file with Vim, or with a here-document: cat > ~/.ssh/config <<'EOF', the lines, then EOF.

Your turn

(1) Make an ed25519 key pair. (2) Install your public key on web. (3) Add a shop entry to ~/.ssh/config that goes to web as learner. (4) Run ssh shop hostname: it should print web, logging in with your key and no password.

Next