Learn SSH: CLI Commands

1 minute read

In this article series, I will explain how to use a command-line terminal to connect to secure shell (SSH) servers, using the config file for quick access to frequently used servers, and setting up an SSH server on macOS, Ubuntu, or CentOS.

Table of Contents:

Introduction
SSH CLI Commands
SSH Config File

Establish SSH Connection

To SSH to a remote server with a username and password, type the following command in a terminal:

ssh username@server_address

You will be prompted for a password.

To SSH to a remote server with a private key, type the following command in a terminal:

ssh username@server_address -i ~/path/to/private/key

Replace ~/path/to/private/key with the actual path to your private key.

To connect to a remote server on a specific port, use the -p flag:

<pre class="wp-block-preformatted" id="block-cead4bd1-5df7-4d66-8299-be9bc48cdfb4">ssh username@server_address -p port_number

or

<pre class="wp-block-preformatted" id="block-0798b8af-82cd-4219-ad7e-8482c6631131">ssh username@server_address -i ~/path/to/private/key -p port_number

Replace port_number with the actual port number of the remote server.

Local Forward

To access a remote service, such as a database server on your local machine, you can use local port forwarding:

ssh -L localPort:server_address:remotePort username@server_address

For example, if the service you are trying to access locally is accessible on the remote server on port 5555, you can use the following command to get access to that service on a local port, such as 5657:

ssh -L 5657:server_address:5555 username@server_address

Now you can connect to the service using localhost:5657 or 127.0.0.1:5657.

Remote Forward

To access a local service on the remote server, you can use remote port forwarding:

ssh -R localPort:server_address:remotePort username@server_address
Jumpbox

To access a protected server through another accessible server, use the -j flag. Consider server_a as the jump box and server_b as the protected server, you’re trying to reach:

Local –> server_a –> server_b

ssh -J username_a@server_a username_b@server_b 

If you need to jump through more servers, try the following command:

Local –> server_a –> server_b –> server_c

ssh -J username_a@server_a,username_b@server_b username_c@server_c
Socks Proxy

To access the network and browse the private web pages on a remote server, you can create a SOCKS proxy. Choose a port number for your proxy, such as 8080, and create the link as:

<pre class="wp-block-preformatted" id="block-ec90aa8d-5b79-485b-85ff-c45e2af42066">ssh -D 8080 username@server_address

Now, set up a proxy on your local machine/browser to 127.0.0.1:8080 address and port.

Let me know your questions and comments in the comment section.

Next article in the series: SSH Config File