← All lessons
System administration · Lesson 6 of 7

SSH

SSH (secure shell) opens a terminal on another machine over an encrypted connection. It's how almost every Linux server is run.

$ ssh sam@203.0.113.20
sam@server:~$ hostname
server
sam@server:~$ exit

Passwords work, but keys are safer and quicker. A key pair is two files: a private key that never leaves your computer, and a public key you put on each server. Make a pair once with ssh-keygen -t ed25519; the files go in ~/.ssh/. Then ssh-copy-id sam@203.0.113.20 installs the public key on the server, in ~/.ssh/authorized_keys, and from then on you log in without the password.

$ ssh-keygen -t ed25519
$ ssh-copy-id sam@203.0.113.20
$ ssh sam@203.0.113.20

Keep the private key private: the .ssh folder should be 700 and the key 600, and SSH refuses to use a key that others can read. Give it a passphrase so a stolen laptop doesn't mean a stolen key.

To copy files, scp file.txt sam@server:/tmp/ sends one across (swap the order to fetch), and rsync -av site/ sam@server:/var/www/site/ copies a folder and, next time, only what changed.

Once keys work, harden the server in /etc/ssh/sshd_config: PasswordAuthentication no stops password guessing, and PermitRootLogin no stops anyone logging in straight as root. Restart the SSH service, and keep your current session open while you test a new login in a second window, so a mistake can't lock you out.

Short names save typing. In ~/.ssh/config on your computer, a block like Host web with HostName 203.0.113.20 and User sam lets you just type ssh web.

Practice

Log in as sam to the server 198.51.100.7.

More info

Quick reference

ssh user@hostLog in to another machine.
ssh-keygen -t ed25519Make a key pair in ~/.ssh.
ssh-copy-id user@hostInstall your public key there.
scp file user@host:pathCopy a file across.
rsync -av dir/ user@host:dir/Copy a folder; next time only changes.
PasswordAuthentication noKeys only (in sshd_config).
~/.ssh/configShort names for servers.

The other Linux courses