Open In App

How to execute commands remotely using SSH in Linux?

Last Updated : 02 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Many times users need to work in remote systems. For which they have to log in to the remote server, execute certain commands and come out of that session. Is it possible to perform all these actions locally? Yes, it’s possible using ssh client. In this article, we will see different ways of running remote commands locally using ssh.

Pre-requisite

  • Any Linux distribution.
  • Install OpenSSH and enable SSH service.
  • Generate SSH key pairs to execute remote commands from the local server to avoid entering passwords.
  • Require commands to be executed with root access or sudo privilege.

1. Single command execution

Let us execute single command ‘date’ to fetch from the remote machine,

 

2. Command redirection

It’s possible to redirect the output of a command executed on the remote server to the local machine using the redirection operator(>),

 

3. Multi-command execution

To execute multiple commands, each command needs to be separated using a semicolon(;) to be enclosed within a single quote or double quote,

 

4. Multi-command execution using pipe

Using an unnamed pipe, let us try to see when the root user last logged onto the remote server,

 

5. Script execution

Remote command execution is not limited to commands, it’s possible to execute even a script located in a remote server provided the script exists. We have to provide the absolute path of the script in the remote machine.

Here, a script is written in a remote server(10.21.42.166) to print the name of the operating system using ‘uname’ command,

 

Now let us run it,

 

The script doesn’t have to execute permission, we got a permission denied error. After changing the permission, the script ran successfully.

 

6. Command execution with privileges

At times, we may need to execute commands with elevated privileges. The test user in the remote server doesn’t have to write permission in the /etc/ directory.

 

We have used the ‘-t‘ option with the SSH command, allowing pseudo-terminal allocation. as sudo command requires an interactive terminal hence this option is necessary.

 

The file got created on a remote server,

 

Thus we have a good understanding of remote command execution for single, multi-commands, using pipe, using redirection, script execution, and running the command with privilege which would definitely help for easy remote access, any kind of automation, etc.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads