Bash Remote Connect

SSH opens an encrypted shell on a remote machine, turning any server into a command line you can work in as if you were sitting in front of it.

What Is SSH?

SSH (Secure Shell) opens an encrypted connection to a remote machine's SSH server, usually listening on port 22, and gives you an interactive shell, or lets you run a single command, without sending your password or data in plain text.

Connecting to a Remote Server

The basic form is ssh user@host. The first time you connect to a new host, SSH shows its key fingerprint and asks you to confirm it before adding the host to your local list of known hosts.

First Connection to a Server

$ ssh deploy@203.0.113.42
The authenticity of host '203.0.113.42 (203.0.113.42)' can't be established.
ED25519 key fingerprint is SHA256:7hK2f9QpYQqzM1nE0v6s8u5c3aB1dW2xR4tL9oCkP0Q.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '203.0.113.42' (ED25519) to the list of known hosts.
deploy@203.0.113.42's password:
Welcome to Ubuntu 22.04.4 LTS (GNU/Linux 5.15.0-105-generic x86_64)
deploy@web01:~$

Connecting with a Non-Default Port or Key

Use -p to specify a non-standard SSH port and -i to point at a specific private key file instead of the default one in ~/.ssh/. Key-based logins skip the password prompt entirely once the matching public key is installed on the server.

Using a Custom Port and Identity File

$ ssh -p 2222 -i ~/.ssh/id_ed25519_deploy deploy@203.0.113.42
Enter passphrase for key '/home/maria/.ssh/id_ed25519_deploy':
Welcome to Ubuntu 22.04.4 LTS (GNU/Linux 5.15.0-105-generic x86_64)
deploy@web01:~$

Running a Single Remote Command

You do not need a full interactive session just to run one command. Append the command after the host and SSH executes it remotely, prints the output locally, and closes the connection automatically.

Running a Command Without an Interactive Shell

$ ssh deploy@203.0.113.42 "df -h /"
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        40G   18G   20G  48% /
  • ~/.ssh/config - store per-host shortcuts (hostname, user, port, key) so you can just type ssh myserver
  • ssh-keygen -t ed25519 - generate a new key pair for passwordless login
  • ssh-copy-id user@host - copy your public key to a server's authorized_keys automatically
  • ssh -L 8080:localhost:80 user@host - forward a local port through the remote server (tunneling)
Note: Set up key-based authentication with ssh-copy-id once, and future ssh and scp connections to that server stop asking for a password.
Note: Never share your private key file (id_rsa, id_ed25519, etc). Only the matching .pub file is meant to be copied to servers.