Lesson 92: ssh Command
In this lesson, you'll learn how to use the ssh command to securely connect to remote Linux hosts, execute commands, copy files, and configure the SSH server.
Secure Shell (SSH) is a widely adopted network protocol that allows us to interact with remote hosts in a secure way.
It provides security by encrypting all communication between them.
Connect to a Remote Linux Host
There are various ways to interact with remote Linux hosts using protocols such as telnet, ftp, netcat, etc.
However, these are not secure due to the absence of encryption. We can use the SSH protocol to allow secure communication between the hosts.
We have to use an SSH client to interact with the remote host. There are plenty of GUI and CLI-based clients available for Linux.
However, here we will use a command-line utility called ssh. By default, the ssh utility is available on most Linux distributions.
ssh Command Syntax
The syntax of the SSH command is as follows:
$ ssh [OPTIONS] [COMMANDS] [ARGS]
Here, the square brackets ([]) represent the optional arguments, whereas angular brackets (<>) represent the mandatory arguments.
ssh Command Options
| Option | Description |
|---|---|
-l USER |
Specify the login username |
-p PORT |
Connect to a specific port (default: 22) |
-C |
Enable compression for the SSH connection |
-v |
Enable verbose mode (verbosity level 1) |
-vv |
Enable verbose mode (verbosity level 2) |
-vvv |
Enable verbose mode (verbosity level 3) |
-s |
Read script from standard input (used with bash) |
-r |
Recursively copy directories (used with scp) |
Let's connect to the remote host using the ssh client:
$ ssh -l root 192.168.168.129
In this example, we specified the login name using the -l option, and the destination is 192.168.168.129.
The SSH connection gets established after entering the correct password. Now, we can execute commands on the remote host just like the local system.
# hostname
server2.tecmint.com
To terminate the session, we can use the exit command or the Ctrl+D key combination.
It is important to note that we have to authenticate with the remote host for each new session.
To avoid entering passwords each time, we can set up an SSH passwordless login.
1. Execute Commands on the Remote Host
In the previous section, we saw how to establish a connection with a remote host, which is suitable only when we are going to use the remote host for a longer duration.
Sometimes, we just need to execute one or two commands on the remote host. In such cases, we can execute those commands without creating a long-term session.
Let's execute the hostname command on the remote host:
$ ssh -l root 192.168.168.129 hostname
server2.tecmint.com
In a similar way, we can execute multiple commands on a remote Linux machine:
$ ssh -l root 192.168.168.129 'hostname; pwd'
server2.tecmint.com
/root
It is important to note that the commands must be enclosed within the quotes and separated by the semi-colon (;) character.