Ravindra BagaleCourses & study guides मराठी

Chapter 4: Linux Ops Refresh for DevOps

DevOps

4.6 SSH keys, scp, rsync — one-liners

Why: the problem

Think of Razorpay. A DevOps engineer must copy a new release to five servers, fetch a log file from one server, and keep a folder of static files in sync with a backup server every night. Doing this with copy and paste or with a password typed every time is slow and unsafe. SSH keys solve the login part: a key pair, where the private key stays on your laptop and the public key goes on the server. Then three tools do the copying. ssh runs commands on a server. scp copies single files. rsync copies whole folders and sends only what changed, so a second run is very fast. In this lesson you will create a key, log in without a password, copy files both ways, sync a folder with a dry run first, and set up an SSH config file so long commands become short names. You will also learn the three rules that keep keys safe.

What we will build

You will use two machines: your laptop (or a lab container) and one Ubuntu 24.04 EC2 server. You will create an ed25519 key, put the public key on the server, and log in. You will write ~/.ssh/config with a short name for the server. Then you will deploy a small website folder with scp, then with rsync and a dry run, then fetch logs back. Finally you will see a jump host (bastion) setup that many companies use for private servers.

What: every term in plain English

  • SSH — Secure Shell. An encrypted way to log in to and run commands on another machine.
  • Key pair — Two files. The private key is secret and stays with you. The public key can be shared.
  • Private key — Your secret file, like ~/.ssh/id_ed25519. Never share it or put it in Git.
  • Public key — The .pub file. You put it on servers in ~/.ssh/authorized_keys.
  • authorized_keys — File on the server listing public keys allowed to log in as that user.
  • known_hosts — File on your laptop that remembers each server fingerprint, to stop fake servers.
  • scp — Secure copy. Copies files over SSH.
  • rsync — Copies folders over SSH and sends only changes. Has a dry run mode.
  • ~/.ssh/config — A file of short names and settings for your servers.
  • Bastion — A jump server in a public subnet used to reach private servers.
Make a key pair Copy the public key to the server Log in with the new key Add a short name Use the short name Copy a file Sync a folder
Key on laptop, public key on server, then scp and rsync, top to bottom

How: step by step

  1. Make a key pair

    ssh-keygen -t ed25519 -C "ravi@laptop" -f ~/.ssh/id_ed25519
    

    What it does: Creates the private and public key. Add a passphrase for real use.

    Output

    Your identification has been saved in /home/ravi/.ssh/id_ed25519
    Your public key has been saved in /home/ravi/.ssh/id_ed25519.pub
    
  2. Copy the public key to the server

    ssh-copy-id -i ~/.ssh/id_ed25519.pub -o "IdentityFile ~/.ssh/lab.pem" ubuntu@13.233.10.20
    

    What it does: Adds your public key to authorized_keys on the server, using the AWS key once.

    Output

    Number of key(s) added: 1
    
  3. Log in with the new key

    ssh -i ~/.ssh/id_ed25519 ubuntu@13.233.10.20 hostname
    

    What it does: Runs one command on the server and comes back.

    Output

    ip-10-0-1-20
    
  4. Add a short name

    nano ~/.ssh/config
    

    What it does: Paste the config from Example 1.

    Output

    (file saved)
    
  5. Use the short name

    ssh web1 uptime
    

    What it does: Same login, much shorter.

    Output

    11:10:05 up 3 days,  load average: 0.05, 0.03, 0.00
    
  6. Copy a file

    scp ./index.html web1:/tmp/
    

    What it does: Sends one file to the server.

    Output

    index.html  100%  612   20.1KB/s   00:00
    
  7. Sync a folder

    rsync -avz --dry-run ./site/ web1:/var/www/site/
    

    What it does: Shows what would change, without changing anything.

    Output

    sending incremental file list
    index.html
    css/app.css
    

Example 1: SSH config with short names and safe permissions

Stack. OpenSSH 9.6

Goal. SSH config with short names and safe permissions.

~/.ssh/config

Host web1
    HostName 13.233.10.20
    User ubuntu
    IdentityFile ~/.ssh/id_ed25519
    IdentitiesOnly yes

Host web2
    HostName 13.233.10.21
    User ubuntu
    IdentityFile ~/.ssh/id_ed25519

Host *
    ServerAliveInterval 30
    ServerAliveCountMax 4

Lock it down and test

chmod 700 ~/.ssh
chmod 600 ~/.ssh/config ~/.ssh/id_ed25519
chmod 644 ~/.ssh/id_ed25519.pub
ssh web1 'whoami; hostname; cat ~/.ssh/authorized_keys | wc -l'
for h in web1 web2; do ssh "$h" 'echo "$(hostname) disk $(df -h / | tail -1 | tr -s " " | cut -d" " -f5)"'; done

What each line does

  • Host web1 — The short name you will type.
  • HostName — The real IP or DNS name.
  • IdentityFile — Which private key to use for this host.
  • IdentitiesOnly yes — Use only that key, not every key in your agent. Avoids "too many authentication failures".
  • ServerAliveInterval 30 — Sends a small ping every 30 seconds so idle sessions do not drop.
  • chmod 600 — ssh refuses config and keys that others can read.
  • for h in web1 web2 — Runs the same check on many servers in one line.

Green output

ubuntu
ip-10-0-1-20
2
ip-10-0-1-20 disk 31%
ip-10-0-1-21 disk 44%

Expected result. Short names work and you checked disk on two servers in one line.

Example 2: Deploy a website folder with scp, then rsync

Stack. scp, rsync 3.2

Goal. Deploy a website folder with scp, then rsync.

Make the site

mkdir -p site/css
echo "<h1>Menu v1</h1>" > site/index.html
echo "h1{color:#c00}" > site/css/app.css
ssh web1 'sudo mkdir -p /var/www/site && sudo chown ubuntu:ubuntu /var/www/site' 

scp: simple, copies everything

scp -r site/* web1:/var/www/site/
ssh web1 ls -R /var/www/site

rsync: dry run, then real, then only changes

echo "<h1>Menu v2</h1>" > site/index.html
rsync -avz --dry-run --delete site/ web1:/var/www/site/
rsync -avz --delete site/ web1:/var/www/site/
rsync -avz --delete site/ web1:/var/www/site/

What each line does

  • scp -r — Copies a folder and everything inside. Always copies all files again.
  • rsync -a — Archive: keeps times, permissions and folders.
  • -v -z — Verbose list, and compress on the way.
  • --dry-run — Shows the plan only. Always do this first with --delete.
  • --delete — Removes files on the server that you deleted locally. Powerful, so dry run first.
  • site/ with a slash — Copies the contents of site. Without the slash you get /var/www/site/site.

Green output

index.html    100%   19   0.6KB/s   00:00
app.css       100%   15   0.5KB/s   00:00
/var/www/site:
css  index.html
/var/www/site/css:
app.css
sending incremental file list
index.html
sent 180 bytes  received 41 bytes  (DRY RUN)
sending incremental file list
index.html
sent 180 bytes  received 41 bytes  total size is 34
sending incremental file list
sent 98 bytes  received 12 bytes  total size is 34

Expected result. The third rsync sent nothing because nothing changed. That is why rsync is used for deploys and backups.

Example 3: Fetch logs back and run remote commands safely

Stack. scp, rsync, ssh

Goal. Fetch logs back and run remote commands safely.

Pull files from the server

mkdir -p incident-logs
scp web1:/var/log/nginx/error.log incident-logs/web1-error.log 2>&1 || ssh web1 'sudo cat /var/log/nginx/error.log' > incident-logs/web1-error.log
rsync -avz --rsync-path="sudo rsync" web1:/var/log/nginx/ incident-logs/web1-nginx/
ls -lh incident-logs incident-logs/web1-nginx | head

Run a remote script without copying it

cat three-checks.sh | ssh web1 'bash -s' -- nginx 80
ssh web1 'sudo systemctl is-active nginx && curl -sI localhost | head -1' 

What each line does

  • scp web1:path local — Server first, laptop second: copies from the server to you.
  • sudo cat > file — Log files need root. This reads with sudo on the server and saves on the laptop.
  • --rsync-path="sudo rsync" — Runs rsync as root on the server side, so it can read protected logs.
  • cat script | ssh web1 bash -s — Runs your local script on the server without copying it. Words after -- become $1 and $2.
  • ssh web1 command — Runs one command and returns. Use quotes around the whole command.
  • && — The curl runs only if nginx is active.

Green output

-rw-r--r-- 1 ravi ravi 4.1K Oct 25 11:14 web1-error.log
incident-logs/web1-nginx:
-rw-r----- 1 ravi ravi  22K access.log
-rw-r----- 1 ravi ravi 4.1K error.log
active
1 process  OK   nginx is running
2 port     OK   something listens on 80
3 disk     OK   root disk 31% used
active
HTTP/1.1 200 OK

Expected result. You collected logs for a ticket without logging in by hand, and checked the service remotely.

Example 4: Reach a private server through a bastion

Stack. OpenSSH ProxyJump, AWS VPC

Goal. Reach a private server through a bastion.

~/.ssh/config addition

Host bastion
    HostName 13.233.50.5
    User ec2-user
    IdentityFile ~/.ssh/id_ed25519

Host app-private
    HostName 10.0.2.15
    User ec2-user
    IdentityFile ~/.ssh/id_ed25519
    ProxyJump bastion

Use it

ssh app-private hostname
scp ./release.tar.gz app-private:/tmp/
ssh -L 5433:mydb.abc123.ap-south-1.rds.amazonaws.com:5432 bastion -N &
sleep 2; ss -tln | grep 5433

What each line does

  • ProxyJump bastion — First connect to bastion, then jump to the private IP. The key stays on your laptop.
  • 10.0.2.15 — A private IP. It cannot be reached from the internet directly.
  • scp through ProxyJump — Copies work through the jump too.
  • ssh -L 5433:db:5432 — A tunnel. Port 5433 on your laptop reaches the RDS database through the bastion.
  • -N — No remote command, only the tunnel.

Green output

ip-10-0-2-15.ap-south-1.compute.internal
release.tar.gz   100%  8.2MB  6.1MB/s   00:01
LISTEN 0 128 127.0.0.1:5433 0.0.0.0:*

Expected result. You reached a private server and a private database safely, without copying your private key to the bastion.

Verify: did it work?

  1. Check key login works without password

    ssh -o BatchMode=yes web1 true && echo key-login-ok
    

    What it does: BatchMode fails instead of asking for a password.

    Output

    key-login-ok
    
  2. Check site files match

    rsync -avzn --delete site/ web1:/var/www/site/
    

    What it does: A dry run that lists nothing means both sides match.

    Output

    sending incremental file list
    sent 98 bytes  received 12 bytes
    

When it is red 1

Permission denied (publickey).

Cause. The server does not have your public key, or ssh used the wrong key or user.

Fix, step by step

  1. Run ssh -v web1 and read which keys it offered.
  2. Check the user: ubuntu for Ubuntu AMIs, ec2-user for Amazon Linux.
  3. Check the server ~/.ssh/authorized_keys and its permissions: folder 700, file 600.

When it is red 2

WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!

Cause. The server fingerprint changed. Often a new EC2 with the same IP, but it can be an attack.

Fix, step by step

  1. Confirm with your team that the server was replaced.
  2. ssh-keygen -R 13.233.10.20 removes the old line.
  3. Connect again and accept the new fingerprint.

When it is red 3

ssh: connect to host 13.233.10.20 port 22: Connection timed out

Cause. Network block. Security group, NACL or firewall does not allow your IP on port 22.

Fix, step by step

  1. Check the EC2 security group allows port 22 from your current IP.
  2. Check the server is running and has a public IP.
  3. Try from another network to rule out office firewalls.

Cleanup

  1. Close the tunnel

    kill %1
    

    What it does: Stops the background SSH tunnel.

    Output

    (no output)
    
  2. Remove the lab site

    ssh web1 "rm -rf /var/www/site"
    

    What it does: Deletes the demo folder on the server, after checking the path.

    Output

    (no output)
    

Ravindra Bagale's Tip

Keep the private key only on your laptop. On the server keep only .pub. In rsync, use --dry-run first. Keep that in mind!

Practice tasks

Easy Key login

Why: Passwords on servers are a security risk.

What to do: Log in to a server with your own key only.

How:
  1. ssh-keygen, ssh-copy-id, ssh -o BatchMode=yes

Check: key-login-ok is printed.

Medium rsync speed test

Why: See why rsync wins.

What to do: Sync a folder of 500 files twice and compare times.

How:
  1. time rsync -az ... twice

Check: The second run is much faster.

Hard Bastion jump

Why: Private subnets are normal in companies.

What to do: Reach a private EC2 through a bastion with ProxyJump.

How:
  1. Two EC2s, one public, one private.

Check: hostname of the private server prints on your laptop.

Easy Say SSH keys, scp and rsync in two lines

Why: If you can say it simply, you understand it. Juniors and interviewers both want the short version first.

What to do: Write two short lines about SSH keys, scp and rsync for a fresher who knows only basic Linux commands.

How:
  1. Write the problem it solves.
  2. Write the one command you use for it.
  3. Read it aloud to a friend.

Check: A fresher understands it without asking a question.

Easy Make a safe practice server

Why: Ops commands can stop services or fill disks. Practice on a machine you can throw away.

What to do: Start a throwaway Ubuntu machine and do this lesson there.

How:
  1. docker run -it --rm --name ops-lab ubuntu:24.04 bash
  2. Or launch a t3.micro Ubuntu 24.04 EC2 with port 22 open only to your IP.
  3. Delete it when you are done.

Check: All practice happens on the lab machine, not on a real server.

Medium Repeat it on Amazon Linux

Why: Companies use both Ubuntu and Amazon Linux. Package names and log files differ a little.

What to do: Do the main steps of this lesson again on Amazon Linux 2023.

How:
  1. docker run -it --rm amazonlinux:2023 bash
  2. Install tools with dnf instead of apt.
  3. Note every difference in your notes.

Check: You can list two differences between Ubuntu and Amazon Linux for this lesson.

Medium Break it on purpose

Why: You must know the red message by face. In a real outage there is no time to read slowly.

What to do: Cause one error from the "When it is red" part of this lesson and fix it.

How:
  1. Follow the error section.
  2. Copy the exact message into your notes.
  3. Write the fix in one line.

Check: You fixed it using only the steps, without searching the web.

Medium Write a one-page runbook

Why: At 2 a.m. nobody remembers the right command. A short page saves the on-call person.

What to do: Write a runbook page for this lesson.

How:
  1. Title, when to use, exact command, how to check, how to undo.

Check: A teammate can follow it alone.

Hard Explain it like an interview

Why: Interviewers want real stories, not definitions.

What to do: Record a 60 second answer about this lesson.

How:
  1. Say the problem, the command you ran, and one error you hit.

Check: Your answer has a real command and a real error message.

Hard Draw the flow top to bottom

Why: A drawing shows the order of checks and what happens on failure.

What to do: Draw this lesson as boxes from top to bottom.

How:
  1. Start at the user complaint, show each check as a box, end at the fix.

Check: Each box matches a real command you ran.

Homework: try at home

Try at home

At home, launch one EC2 server, create your own ed25519 key, add it with ssh-copy-id, and write a ~/.ssh/config entry. Deploy a small site folder with rsync using a dry run first. Then change one file and prove rsync sends only that file.

Recap

  • A key pair has a secret private key and a shareable public key.
  • Public keys go in authorized_keys on the server.
  • ~/.ssh/config gives servers short names.
  • scp copies files, rsync syncs folders with dry run and only changes.
  • Reach private servers with ProxyJump, never copy private keys to servers.

FAQ

Should I use a passphrase on my key?

Yes for real use. ssh-agent remembers it so you type it once per session.

RSA or ed25519?

ed25519 is newer, shorter and fast. Use it unless an old system needs RSA.

Can I put my private key in a Git repo for the team?

Never. Each person has their own key. Jenkins uses credentials storage.

What is AWS Systems Manager Session Manager?

A way to get a shell on EC2 without opening port 22 at all. Many companies prefer it.

Why does rsync ask for a password?

It uses SSH. Fix SSH key login first and rsync will follow.

Interview questions

  1. How does SSH key authentication work?

    The server has your public key. On login it sends a challenge that only your private key can sign. The private key never leaves your machine.

  2. scp vs rsync?

    scp copies every file every time. rsync compares and sends only differences, can delete extra files, and has a dry run.

  3. What is a bastion host?

    A hardened jump server in a public subnet. Admins SSH to it and then to private servers, often with ProxyJump.

  4. How do you fix Permission denied (publickey)?

    Check the user name, the key used with ssh -v, and the server authorized_keys and folder permissions.

  5. How do you keep private keys safe?

    600 permissions, a passphrase, never in Git or chat, separate keys per person, and rotate them when people leave.

Quick quiz

Q1. Which key file must never be shared?

The private key, the one without .pub.

Q2. Which file on the server lists allowed keys?

~/.ssh/authorized_keys

Q3. Why use rsync instead of scp for deploys?

rsync sends only changes and supports dry run and delete.

Q4. What does ProxyJump do?

Connects through a bastion to a private server.

Q5. What does a trailing slash on site/ mean in rsync?

Copy the contents, not the folder itself.

Did you understand? Let us try it once more.

Ravi Sir's Cards for this lesson

मराठी cards