If you are using a Linux local computer, the simplest way to connect to a remote server via SSH is using openSSH client in your Terminal.

Table of Contents

Connecting to a remote server

Connecting to a remote server with a private key is very straightforward:

ssh -i <private key file> <username>@<public IP or public DNS>

This is an example:

ssh -i ./privatekey.pem ubuntu@123.456.789

If the terminal shows this question: Are you sure you want to continue connecting (yes/no/[fingerprint])?, type yes to save the fingerprint of the key.

If your remote server doesn’t use port 22 for SSH, type -p <PORT> at the end of the command.

ssh -i ./privatekey.pem ubuntu@123.456.789 -p 2222

Execute a command on the remote server

You can also execute a command on the remote server just when it connects, simply type it at the end:

ssh -i ./privatekey.pem ubuntu@123.456.789 cat /etc/os-release
  • You may need to add ;exit to automatically close the connection when previous command ends its execution.

Redirecting ports with SSH

If you want to use a non-encrypted service (like VNC), you can encrypt it with SSH, doing port forwarding.

ssh -i ./privatekey.pem -L <LOCAL-PORT>:<REMOTE_PORT> ubuntu@123.456.789

-L stands for “local redirection”. This is an example using VNC default port:

ssh -i ./privatekey.pem -L 5900: ubuntu@123.456.789

Then, you can access remote VNC with IP and port 5900 ( is an special IP which refers to the device itself, in this case your local computer. You can also type localhost instead of this IP).

X11 forwarding

You can also open remote X programs through SSH (remote server needs to have installed the X Window System). Check line: X11Forwarding yes inside /etc/ssh/sshd_config (on the server).

ssh -X <username>@<server>
# or for trusted X11 forwarding
ssh -Y <username>@<server>

Then, you can run any X program from the remote machine.

Using ~/.ssh/config file

Creating this file, you can add aliases to your connections, so you don’t need to remember server info all the time:

Host your_alias
  HostName ip
  User user
  Port 22
  IdentityFile full/path/to/privatekey

Then, you simply type ssh your_alias to connect.

If you have any suggestion, feel free to contact me via social media or email.