SSH for developers

By

Updated

Tagged: CLI

SSH for developers: connect to VPS servers, create keys with ssh-keygen, use ~/.ssh/config aliases, and copy files with scp or rsync.

SSH lets you open an encrypted connection to another machine. You use it to manage servers, run remote commands, copy files, create tunnels, and authenticate Git operations.

The command looks simple:

ssh deploy@203.0.113.10

There are two separate trust questions behind it:

  1. Is this the server I meant to reach?
  2. Can I prove to that server who I am?

Host keys answer the first question. User keys (or another authentication method) answer the second.

What happens during an SSH connection

SSH does more than encrypt a terminal session.

First, your client opens a TCP connection to the server. Both sides exchange protocol versions and agree on the encryption, key exchange, host key, and integrity algorithms they support.

The key exchange creates temporary session keys, and the server signs part of that exchange with its host private key. Your client checks that signature against the host key stored in known_hosts.

User authentication only starts after that.

With public key authentication, the server checks whether your public key is authorized. Your client signs data tied to the current connection with the private key, and the server verifies that signature with the public key. The private key never travels across the network.

Once you’re authenticated, SSH opens one or more channels inside the encrypted connection. An interactive shell uses one channel, while a remote command, file transfer, or forwarded port can use another.

Here’s the complete flow:

Open a TCP connectionAgree on algorithms and session keysProve the server identityCheck known_hostsProve the user identityOpen encrypted channelsYour computerSSH serverYour computerSSH server

Keep this flow in mind when something breaks. Each step can fail on its own: you might reach the server and fail the host key check, pass the host check and have your key rejected, or authenticate fine and still see a forwarded port refuse to answer.

Connect to a server

The basic syntax is:

ssh user@host

Pass -p when the server listens on a different port:

ssh -p 2222 deploy@203.0.113.10

That IP address is from the range reserved for documentation, so replace it with your server’s address.

If you’re setting up your first server, the free Ubuntu VPS course walks through provisioning, secure access, and deployment. The free Networking Foundations course covers addresses, ports, and routes.

Verify the host key

The first time you connect, SSH shows a fingerprint like this:

The authenticity of host '203.0.113.10' can't be established.
ED25519 key fingerprint is SHA256:...
Are you sure you want to continue connecting?

Don’t type yes by reflex.

Check that fingerprint against a value from another trusted source. Your hosting provider might show it in the dashboard or console, or a system administrator can give it to you directly.

Once you approve it, SSH saves the host key in:

~/.ssh/known_hosts

Future connections compare the server against that saved key.

If the key changes, SSH warns you. Maybe the server was rebuilt, or maybe the address now points to a different machine or someone is intercepting the connection.

Investigate before clearing the old entry. Once you’ve confirmed the change is real, remove the old host entry with:

ssh-keygen -R 203.0.113.10

Then connect again and verify the new fingerprint.

Never disable strict host checking to silence the warning. Without it, you could be typing your commands into an attacker’s machine over a perfectly encrypted connection.

Create an SSH key pair

Key-based authentication uses two related files:

  • the private key stays on your machine
  • the public key goes on the server

Generate an Ed25519 key with:

ssh-keygen -t ed25519 -C 'flavio@macbook'

SSH asks where to save it. The default files are:

~/.ssh/id_ed25519
~/.ssh/id_ed25519.pub

The .pub file is public, so you can put it on servers and Git hosting services.

The file without .pub is private. Never email it, paste it into a dashboard, or commit it.

Set a passphrase when prompted. It encrypts the private key on disk, so someone who steals the file can’t use it right away.

The passphrase never goes to the server. Your computer only uses it locally to unlock the private key.

You can check a public key’s fingerprint with:

ssh-keygen -lf ~/.ssh/id_ed25519.pub

This comes in handy when a server, Git provider, or teammate lists several keys. Compare fingerprints instead of guessing from filenames.

Install the public key on the server

If the server accepts a password for initial setup, copy your key over with:

ssh-copy-id deploy@203.0.113.10

That appends your public key to the remote user’s ~/.ssh/authorized_keys file and sets the right permissions.

Some hosting providers install a public key when they create the server. When they do, you don’t need password login or ssh-copy-id at all.

If you’re installing a key by hand, copy the entire .pub line and run these commands on the server:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

The account has to own both the directory and the file. OpenSSH usually rejects authorized_keys if another user can modify it or its parent directory.

Each line can also limit what a key is allowed to do. For example, you can lock an automated deployment key down to one command and nothing else:

command="/usr/local/bin/deploy-notes",restrict ssh-ed25519 AAAAC3...

restrict turns off features like port forwarding, agent forwarding, and pseudo-terminal allocation. The forced command ignores whatever command the client asked to run.

Save restrictions like this for automation keys. Your normal interactive key needs a shell, so this setup would be too tight for it.

Test the key in a new terminal:

ssh deploy@203.0.113.10

Keep your original session open while you test, so you can still fix things if the new login fails. Always verify a second connection works before turning off password login.

Remember that the server authorizes the key per user. A key added for deploy doesn’t automatically grant access as root.

Protect local SSH files

SSH expects tight permissions on your local SSH directory and keys:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519
chmod 600 ~/.ssh/config
chmod 644 ~/.ssh/id_ed25519.pub

If other users on the machine can read a private key, SSH may refuse to use it.

Be careful with backups too. A backup containing an unencrypted private key is another copy an attacker can steal.

Use ~/.ssh/config

Typing a user, address, port, and key every time gets old fast. Put host-specific settings in ~/.ssh/config instead:

Host notes-server
  HostName 203.0.113.10
  User deploy
  Port 2222
  IdentityFile ~/.ssh/notes_server_ed25519
  IdentitiesOnly yes

Now you can connect with:

ssh notes-server

Host is your local alias, and HostName is the real DNS name or IP address.

IdentitiesOnly yes tells SSH to try only the key you configured, instead of offering every key loaded in your agent. That prevents authentication failures when your agent holds a bunch of keys.

SSH reads command-line options first, then your user config, then the system config. For most settings, the first match wins.

Because of that, order matters. Put specific hosts above broad wildcard blocks:

Host production
  HostName 203.0.113.10
  User deploy

Host *.internal.example
  User flavio

You can inspect the final config SSH will apply with:

ssh -G notes-server

This prints the resolved client settings without opening a connection. It’s really helpful when aliases, wildcard blocks, and included files overlap.

If your config grows large, split it up with Include:

Include ~/.ssh/config.d/*

SSH reads included files right at that spot in the file. Keep their permissions as tight as the main config.

Manage several keys

I prefer using separate keys when identities sit behind different security boundaries, like personal Git hosting versus a production server.

Generate a named key with:

ssh-keygen -t ed25519 -f ~/.ssh/notes_server_ed25519

Test it once from the command line:

ssh -i ~/.ssh/notes_server_ed25519 deploy@203.0.113.10

Once that works, move it into ~/.ssh/config.

Using one key for every server is convenient, but if it leaks you have to replace it everywhere. On the other hand, one key per server gets tedious to manage. A middle ground works well: one key for Git hosting, one for production servers, and a separate one for automation.

This is the same key setup you use for Git over SSH.

Use ssh-agent

A passphrase protects your key, but typing it on every connection gets annoying. ssh-agent keeps unlocked keys in memory so you don’t have to.

Start an agent in your shell and add a key:

eval "$(ssh-agent -s)"
ssh-add ~/.ssh/notes_server_ed25519

List the keys currently loaded:

ssh-add -l

Remove a single key:

ssh-add -d ~/.ssh/notes_server_ed25519

Most desktop operating systems already start an agent and tie it into their credential store. Check your operating system’s OpenSSH instructions before adding shell startup commands that spin up a new agent in every terminal.

Avoid agent forwarding by default

Agent forwarding lets a remote host talk back to your local agent:

ssh -A notes-server

That doesn’t copy your private key onto the server, but a privileged attacker on that remote host can still use your forwarded agent to authenticate elsewhere for as long as the connection stays open.

Don’t enable ForwardAgent yes globally. Use a jump host or a tightly scoped deploy key instead whenever you can.

Run one remote command

SSH doesn’t require an interactive shell. You can run a single command and exit right away:

ssh notes-server 'systemctl --user status notes-api'

The remote command’s output prints locally, and its exit status becomes the ssh command’s exit status.

That makes SSH handy in scripts:

if ssh notes-server 'test -f /var/www/notes/current.txt'; then
  echo 'Release marker exists'
else
  echo 'Release marker is missing'
fi

Watch your quoting here. Your local shell parses the command line first, and then the remote shell parses the string it receives. For anything complicated, copy a tested script over to the server and run it there.

Don’t put secrets directly in the command, either. They can end up in shell history, process listings, or logs.

Copy files with scp

Copy a local file to the server:

scp deploy.zip notes-server:/var/www/notes/

Copy a remote log to the current folder:

scp notes-server:/var/log/nginx/error.log ./error.log

Copy a directory recursively:

scp -r ./assets notes-server:/var/www/notes/

scp works great for a handful of files. Check out download a file with scp for more examples.

Synchronize folders with rsync

rsync compares the source and destination and only sends the differences over SSH:

rsync -av ./dist/ notes-server:/var/www/notes/

The trailing slash on ./dist/ means “copy the contents of this folder.” Leave it off, and rsync creates a dist folder inside the destination instead.

When you’re running a sync that can delete files, preview it first with --dry-run:

rsync -av --delete --dry-run \
  ./dist/ notes-server:/var/www/notes/

--delete removes anything on the destination that isn’t in the source. Check the dry-run output, double-check both paths, and only drop --dry-run once you’re sure you want those files gone.

Keep in mind that rsync mirrors two folders rather than backing them up. If you delete a file by mistake on one side, the next sync removes it from the other side too.

Forward a port to your computer

Local port forwarding exposes a remote service on your laptop.

Say Postgres only listens on the server’s loopback interface at port 5432. You can open a tunnel like this:

ssh -N -L 5433:127.0.0.1:5432 notes-server

Now a local client can connect to 127.0.0.1:5433, and SSH forwards that traffic to 127.0.0.1:5432 as seen from notes-server.

-N tells SSH not to run a remote command, so the connection only stays open for forwarding.

You can also tell SSH to exit with an error if it can’t set up the tunnel:

ssh -N \
  -o ExitOnForwardFailure=yes \
  -L 5433:127.0.0.1:5432 \
  notes-server

By default, the local port only listens on your own machine. Don’t bind a database tunnel to every network interface unless other machines truly need access and you know what you’re exposing.

The easiest way to read -L is:

-L local_port:destination_seen_from_server:destination_port

Notice that the destination gets resolved from the SSH server, not from your laptop. That matters when the service uses a private hostname.

Forward a local service to the server

Remote forwarding goes in the other direction.

Say you have an app running on your laptop at port 3000. You can expose it on the server at port 8080 with:

ssh -N -R 8080:127.0.0.1:3000 notes-server

Now a process on notes-server can connect to 127.0.0.1:8080, and SSH sends that traffic back to port 3000 on your laptop.

Remote forwarding is handy for short-lived previews and callback testing. Don’t treat it as a permanent deployment setup.

The SSH server controls whether remote forwarding is allowed, as well as whether the listening port stays on loopback or can bind to other interfaces.

Create a SOCKS proxy

Dynamic forwarding lets each app pick its own destination through your SSH tunnel:

ssh -N -D 1080 notes-server

That opens a SOCKS proxy at 127.0.0.1:1080. Point your browser or any SOCKS-aware client to it, and traffic from that app will exit through notes-server while everything else on your machine uses its normal network path.

Watch out for DNS lookups, though. Some clients resolve hostnames locally before sending traffic through the proxy, so turn on the client’s remote-DNS option if you want DNS queries routed through the tunnel too.

Keep long connections healthy

Networks and firewalls sometimes drop idle connections. You can add per-host keepalives to catch that:

Host notes-server
  ServerAliveInterval 30
  ServerAliveCountMax 3

Here, your SSH client sends a message after 30 seconds of inactivity and gives up after three unanswered replies.

Keepalives detect a dead connection, though they won’t keep a crashed remote process alive. Use tmux, screen, or a service manager for long-running server work.

Leave a stuck session

If a remote shell or network freezes, you can disconnect with SSH’s built-in escape commands. Press Enter, then type:

~.

That closes the connection right away. The escape character has to be at the start of a new line, which is why you press Enter first.

Type ~? to list the other escape commands. Your local SSH client handles these sequences directly rather than the remote shell.

Debug a failed connection

When a connection fails, start by turning on verbose output:

ssh -v notes-server

You can pass -vv or -vvv if you need more detail. The log prints your config, address resolution, host-key negotiation, and authentication attempts, and it usually shows the exact key SSH offered.

Each common error points to a different part of the connection:

ErrorMeaning
Connection timed outRouting, firewall, or wrong address
Connection refusedThe host answered, but nothing is listening on that port
Host key verification failedHost identity is unknown or changed
Permission denied (publickey)The server rejected every offered identity
Too many authentication failuresThe client offered too many keys before trying the right one

Don’t fix connection errors by turning security checks off. Read the verbose output and track down which step is failing.

To test authentication without opening an interactive shell, run:

ssh -o BatchMode=yes notes-server true

BatchMode=yes disables password and passphrase prompts, which makes it useful in scripts and automation because the command fails right away instead of waiting for input.

If you manage the server, watch its logs while you run a test connection. On Ubuntu, a common command is:

sudo journalctl -u ssh --since '10 minutes ago'

The client log shows what your computer tried, and the server log shows why sshd said no. You’ll often need both.

Whenever you edit the server’s SSH configuration, keep your current session open and validate the file before reloading:

sudo sshd -t

No output means the syntax is valid. Before closing your first session, test a second login to make sure your access rules let you in.

Server-side security basics

On a VPS, this is my baseline:

  • a named admin or deployment user instead of routine root login
  • key authentication with a passphrase
  • a firewall that only exposes the ports you need
  • password login disabled only after you’ve confirmed key access works
  • separate keys or users for automation where practical
  • timely operating system and OpenSSH updates

Keep in mind that SSH only protects the connection and checks who’s logging in. It doesn’t make the commands you run safe, so a connected user can still delete files or leak secrets within whatever permissions they have.

If you want to take this further on a real server:

How I use SSH

I put every regular server in ~/.ssh/config. Recording the user, address, port, and identity once in an alias means regular commands, scp, rsync, and Git can all reuse it.

I verify host keys, use passphrases, and leave agent forwarding off. For deployments, I prefer a narrow user and one tested remote script over a long quoted command.

I wouldn’t expose a database publicly just to reach it from my laptop. A local SSH tunnel gives temporary access through the existing authenticated connection.

If you want to go the other way and build an app people SSH into, check out how to build an SSH app like superlogical.jobs.

The free SSH course goes deeper into keys, server hardening, automation, rotation, and recovery. And if you want to see SSH inside a full server workflow, take a look at the Ubuntu VPS course.

Want me to talk about your product? You can sponsor this site.

Related posts about cli: