← Linux and the Command Line Lesson 31 of 51 · 5 XP

ssh, scp and rsync — remote servers

Theory

Machine translation, not yet reviewed by a native speaker.

ssh is an encrypted login to the terminal of a remote machine:

ssh user@203.0.113.10                 # log in
ssh -p 2222 user@server               # a non-standard port
ssh user@server "df -h"               # run one command and leave

Logging in with a password is inconvenient and less secure. The right way is keys:

ssh-keygen -t ed25519                 # create a pair: ~/.ssh/id_ed25519 (private) and .pub (public)
ssh-copy-id user@server               # put the PUBLIC key on the server

The private key is never given to anyone and never put into chats or repositories. Only the .pub goes to the server and to GitHub.

Short server names go in the file ~/.ssh/config:

Host vps
    HostName 203.0.113.10
    User root
    Port 22

After that, ssh vps is enough.

scp copies files over ssh:

scp backup.tar.gz vps:/root/          # from your computer to the server
scp vps:/var/log/app.log .            # from the server to your computer
scp -r site/ vps:/var/www/            # a whole folder

rsync is smart synchronisation: it transfers only the parts of files that have changed. That's much faster for repeated copying and for deployment:

rsync -avz site/ vps:/var/www/site/          # -a archive, -v verbose, -z compression
rsync -avz --delete site/ vps:/var/www/site/ # delete on the server what you don't have
rsync -avzn …                                # -n: a "dry run", changes nothing

The slash at the end of site/ matters: with it, the contents of the folder are copied; without it — the folder itself, into the target.

The Linux built into the browser runs without a network, so try the networking commands on your own computer or a VPS.

Sign up for free to mark finished lessons and track your progress.