Connect to a Remote Linux Server Using SSH

LinuxBeginner
Practice Now

Introduction

In this lab, you will learn the essential skills for connecting to and managing a remote Linux server using the Secure Shell (SSH) protocol. You will begin by setting up the remote environment, which involves installing and configuring the OpenSSH server package. After ensuring the server is ready to accept connections, you will learn how to obtain its IP address, a crucial step for establishing a connection from a client machine.

Once the server is configured, you will practice two primary methods of remote interaction via SSH. First, you will establish a fully interactive shell session, giving you complete command-line access to the remote machine. Second, you will learn how to execute a single, specific command on the remote server without starting a full interactive session, a technique that is highly effective for scripting and automation tasks.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 99% completion rate. It has received a 99% positive review rate from learners.

Install and Configure the OpenSSH Server

In this step, you will install the OpenSSH server package, which allows your system to accept incoming SSH connections. SSH, or Secure Shell, is a cryptographic network protocol for operating network services securely over an unsecured network. The openssh-server package contains the core components for hosting an SSH server.

First, it's a good practice to update your system's package list to ensure you get the latest version of the software. The labex user has sudo privileges, which are required for system-wide package management.

Run the following command to update the package index:

sudo apt-get update

You will see output similar to the following, indicating that the package lists are being fetched from the repositories:

Hit:1 http://archive.ubuntu.com/ubuntu jammy InRelease
Get:2 http://archive.ubuntu.com/ubuntu jammy-updates InRelease [119 kB]
Get:3 http://security.ubuntu.com/ubuntu jammy-security InRelease [110 kB]
...
Fetched 1,845 kB in 2s (1,040 kB/s)
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
All packages are up-to-date.

Now, you can install the openssh-server package using apt-get. The -y flag automatically answers "yes" to any prompts, making the installation non-interactive.

sudo apt-get install -y openssh-server

After the command completes, you should see output confirming the installation and setup of the openssh-server and its dependencies:

Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following additional packages will be installed:
  ncurses-term openssh-sftp-server ssh-import-id
...
Setting up openssh-server (1:8.9p1-3ubuntu0.1) ...
...
Creating SSH2 ECDSA key; this may take some time ...
Creating SSH2 ED25519 key; this may take some time ...
...

The OpenSSH server service, named sshd, should start automatically after installation. You can verify its status using the systemctl command, which is a tool for controlling the systemd system and service manager.

Check the status of the SSH service:

sudo systemctl status ssh

The output should show that the service is active (running). This confirms that the SSH server is ready to accept connections.

● ssh.service - OpenBSD Secure Shell server
     Loaded: loaded (/lib/systemd/system/ssh.service; enabled; vendor preset: enabled)
     Active: active (running) since Mon 2023-10-30 10:30:00 UTC; 5s ago
       Docs: man:sshd(8)
             man:sshd_config(5)
   Main PID: 1234 (sshd)
      Tasks: 1 (limit: 4617)
     Memory: 1.2M
        CPU: 8ms
     CGroup: /system.slice/ssh.service
             └─1234 "sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups"

...

Press the q key on your keyboard to exit the status view and return to the command prompt.

Great! The OpenSSH server is now installed and running on your system. In the next step, you will create a new user for SSH demonstration, then learn how to find the server's IP address and connect to it.

Create a New User for SSH Demonstration

In this step, you will create a new user account that will be used for SSH connections. Since the default labex user has sudo privileges but we don't know its password for SSH authentication, we need to create a dedicated user with a known password for this demonstration.

First, create a new user named sshuser using the adduser command. This command will create the user account and prompt you to set up a password and other details.

sudo adduser sshuser

You will be prompted to enter and confirm a password for the new user. For this lab, use password123 as the password. You will also be asked for additional information like full name, room number, etc., but you can press Enter to skip these fields.

Adding user `sshuser' ...
Adding new group `sshuser' (1001) ...
Adding new user `sshuser' (1001) with group `sshuser' ...
Creating home directory `/home/sshuser' ...
Copying files from `/etc/skel' ...
New password:
Retype new password:
passwd: password updated successfully
Changing the user information for sshuser
Enter the new value, or press ENTER for the default
 Full Name []:
 Room Number []:
 Work Phone []:
 Home Phone []:
 Other []:
Is the information correct? [Y/n] Y

Now verify that the user was created successfully by checking the /etc/passwd file:

grep sshuser /etc/passwd

You should see output similar to:

sshuser:x:1000:1000:,,,:/home/sshuser:/bin/bash

This confirms that the sshuser account has been created with a home directory at /home/sshuser and uses the bash shell. The exact UID (user ID) and GID (group ID) numbers may vary depending on existing users on the system.

You can also verify that the user's home directory was created. Note that you need sudo privileges to access another user's home directory:

sudo ls -la /home/sshuser

The output should show the user's home directory contents:

total 20
drwxr-x--- 2 sshuser sshuser 4096 Jun 30 09:26 .
drwxr-xr-x 5 root    root    4096 Jun 30 09:26 ..
-rw-r--r-- 1 sshuser sshuser  220 Jun 30 09:26 .bash_logout
-rw-r--r-- 1 sshuser sshuser 3771 Jun 30 09:26 .bashrc
-rw-r--r-- 1 sshuser sshuser  807 Jun 30 09:26 .profile

Notice that the home directory has restricted permissions (drwxr-x---), which means only the owner (sshuser) and users in the same group can access it. This is why sudo is required to list its contents.

Perfect! You now have a user account sshuser with the password password123 that you can use for SSH connections in the following steps.

Obtain the SSH Server's IP Address

In this step, you will learn how to find the IP address of your SSH server. An IP address is a unique numerical label assigned to each device connected to a computer network that uses the Internet Protocol for communication. To establish an SSH connection, the client machine needs to know the IP address of the server it wants to connect to.

In a typical scenario with two separate machines, you would use this IP address to connect from the client. However, for this lab, you are working on a single virtual machine which will act as both the SSH server and the SSH client. To connect to the SSH server running on your own machine, you can use a special IP address, 127.0.0.1, also known as localhost. This address always refers to the local machine itself.

Even so, it's an essential skill to know how to find your machine's network-facing IP address. The modern command for this in Linux is ip.

To display information about all network interfaces on your system, use the ip addr command:

ip addr

The output will list all network interfaces, such as lo (the loopback interface), eth0 (the primary Ethernet interface), and possibly docker0 (Docker bridge interface). You are looking for the inet entry under your main network interface, which is typically eth0.

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:16:3e:01:82:ae brd ff:ff:ff:ff:ff:ff
    altname enp0s5
    altname ens5
    inet 172.16.50.114/24 metric 100 brd 172.16.50.255 scope global dynamic eth0
       valid_lft 1892159625sec preferred_lft 1892159625sec
    inet6 fe80::216:3eff:fe01:82ae/64 scope link
       valid_lft forever preferred_lft forever
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
    link/ether 02:42:86:fe:f0:88 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever

In the example above, the primary IP address for the eth0 interface is 172.16.50.114. You may also see a docker0 interface if Docker is installed on the system.

A simpler command to display only the IP addresses of the machine is hostname -I.

hostname -I

This command will print a space-separated list of the machine's IP addresses.

172.16.50.114 172.17.0.1

The output shows multiple IP addresses: the primary network interface IP (172.16.50.114) and the Docker bridge IP (172.17.0.1).

Now you know how to find your machine's IP address. In the next step, you will use the localhost address (127.0.0.1) to connect to the SSH server running on this same machine.

Establish an Interactive SSH Session to the Remote Server

In this step, you will use the ssh client to establish an interactive session with the OpenSSH server you configured. An interactive session gives you a command-line prompt on the remote server, allowing you to execute commands as if you were physically logged into it.

To connect, you use the ssh command followed by the username and the server's address, in the format ssh <user>@<hostname_or_ip>. Since you are connecting to the server running on your own machine (localhost) as the user sshuser, you will use the IP address 127.0.0.1.

Open a terminal and run the following command:

ssh sshuser@127.0.0.1

The first time you connect to any new SSH server, your SSH client will display the server's public key fingerprint and ask you to confirm its authenticity. This is a security measure to prevent "man-in-the-middle" attacks. You should type yes and press Enter to continue.

The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.
ED25519 key fingerprint is SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '127.0.0.1' (ED25519) to the list of known hosts.

After confirming the host key, you will be prompted for the password for the sshuser user on the remote server. Enter the password password123 that you set when creating the user.

sshuser@127.0.0.1's password:

Once you enter the correct password, you will be logged in and presented with the server's welcome message and a new command prompt. Notice how the prompt might change to indicate you are on the remote host.

Welcome to Ubuntu 22.04.x LTS (GNU/Linux x.x.x-xx-generic x86_64)

* Documentation:  https://help.ubuntu.com
* Management:     https://landscape.canonical.com
* Support:        https://ubuntu.com/advantage

sshuser@ubuntu:~$

To confirm you are in a remote session, you can run a command like pwd to print the current working directory.

pwd

The output will show your home directory on the remote machine.

/home/sshuser

To close the interactive SSH session and return to your local machine's shell, simply type exit and press Enter.

exit

You will see a message confirming the connection is closed, and your original command prompt will return.

logout
Connection to 127.0.0.1 closed.

You have now successfully established and closed an interactive SSH session.

Execute a Single Command Remotely via SSH

In this step, you will learn how to execute a single command on a remote server without starting a full interactive session. This is a powerful feature of SSH, widely used in scripts and for automation, as it allows you to quickly retrieve information or perform a task on a remote machine and then immediately disconnect.

The syntax for this is to simply append the command you wish to run to the end of your usual ssh connection string. It's a good practice to enclose the remote command in quotes to prevent the local shell from interpreting it.

Let's try running the hostname command on the remote server. This command prints the system's hostname.

ssh sshuser@127.0.0.1 "hostname"

You will be prompted for the password (password123) just as before. After you enter it, the hostname command will execute on the remote server, its output will be printed to your terminal, and the SSH connection will close automatically.

sshuser@127.0.0.1's password:
iZrj91w6gb8osv0mra83hdZ

Notice that you are immediately returned to your local command prompt without needing to type exit.

You can execute more complex commands as well. For example, let's list the contents of the root directory (/) on the remote server using ls -l /.

ssh sshuser@127.0.0.1 "ls -l /"

Again, enter the password password123 when prompted. The output will be a long listing of the files and directories in the root filesystem of the remote server.

sshuser@127.0.0.1's password:
total 72
lrwxrwxrwx   1 root root     7 Apr 21  2022 bin -> usr/bin
drwxr-xr-x   4 root root  4096 May 30  2023 boot
drwxr-xr-x  19 root root  4080 Jun 30 09:23 dev
drwxr-xr-x 137 root root 12288 Jun 30 09:26 etc
drwxr-xr-x   5 root root  4096 Jun 30 09:26 home
lrwxrwxrwx   1 root root     7 Apr 21  2022 lib -> usr/lib
lrwxrwxrwx   1 root root     9 Apr 21  2022 lib32 -> usr/lib32
lrwxrwxrwx   1 root root     9 Apr 21  2022 lib64 -> usr/lib64
lrwxrwxrwx   1 root root    10 Apr 21  2022 libx32 -> usr/libx32
drwx------   2 root root 16384 Dec 28  2022 lost+found
drwxr-xr-x   2 root root  4096 Apr 21  2022 media
drwxr-xr-x   2 root root  4096 Apr 21  2022 mnt
drwxr-xr-x   5 root root  4096 Feb 27  2023 opt
dr-xr-xr-x 231 root root     0 Jun 30 09:22 proc
drwx------   8 root root  4096 Jun 30 09:26 root
drwxr-xr-x  35 root root  1060 Jun 30 09:30 run
lrwxrwxrwx   1 root root     8 Apr 21  2022 sbin -> usr/sbin
drwxr-xr-x  10 root root  4096 Feb 18  2023 snap
drwxr-xr-x   2 root root  4096 Apr 21  2022 srv
dr-xr-xr-x  13 root root     0 Jun 30 09:22 sys
drwxrwxrwt  18 root root  4096 Jun 30 09:30 tmp
drwxr-xr-x  14 root root  4096 Apr 21  2022 usr
drwxr-xr-x  13 root root  4096 Apr 21  2022 var

This method is incredibly efficient for managing multiple servers or for integrating remote operations into your local shell scripts. You have now learned the two primary ways to use SSH: for interactive sessions and for single command execution.

Summary

In this lab, you learned the fundamental steps to enable and use Secure Shell (SSH) for remote server management. You began by preparing the remote Linux server, which involved updating the package repository index using sudo apt-get update and then installing the openssh-server package. This process configured the system to securely accept incoming SSH connections, automatically starting the sshd service.

Next, you created a dedicated user account (sshuser) with a known password (password123) for SSH authentication purposes, since the default labex user has sudo privileges but lacks a password for SSH connections. You verified the user creation and confirmed the home directory was properly established.

With the server and user account ready, you learned how to obtain the server's IP address, a crucial piece of information for any client to initiate a connection. You then practiced the two primary ways of using SSH: establishing a full, interactive command-line session to work on the remote server directly, and executing a single, non-interactive command remotely, which is highly efficient for scripting and automation tasks.