How To Run Shell Script or Command On Remote With SSH – POFTUT

How To Run Shell Script or Command On Remote With SSH


I want to run my commands securely. Is there any way for this? Yes, there are a lot of options. But the most simple and secure way is running scripts or commands over ssh.

Run Command On Remote System

SSH is a very powerful tool that can invoke provided commands on a remote system or server. We will provide the command and options in a double quote. This command will run current users default shell which is generally bash. In this example, we will run a command on remote IP address 192.168.142.144 and the user will be  ismail

$ ssh ismail@192.168.142.144 "uname -a"
Run Command On Remote System
Run Command On Remote System

Enable Key Based or Passwordless Remote Command Execution

As we can see that in order to run command on remote system we provided password for the given user. This can be prevent automated running or trivial task if we are running remote commands regularly. We can setup key based authentication which will do not ask further command execution. We will use ssh-copy-id to the remote system we wan to run command. For more details:

How To Login To Linux with Passwordless via SSH with Key Based Authentication?

$ ssh-copy-id 192.168.142.144
Enable Key Based or Passwordless Remote Command Execution
Enable Key Based or Passwordless Remote Command Execution

Run Script On Remote System

Bash shell provides some PATH to find provided command in the binaries. If we want to run a script we need to provide the whole path of this script and run on bash shell properly. In this example, we will provide a script which is located at /home/ismail/backup.sh on remote IP address 192.168.142.144 .

$ ssh ismail@192.168.142.144 "/bin/bash /home/ismail/backup.sh"

Run Local Script On Remote System

There is a problem what will be happen if the script is located in local system. Should we copy it to remote system and then run. May be it is solution but more convenient and easy way is echoing script to the remote bash session

$ ssh ismail@192.168.142.144 'bash -s' < cat script.sh
How To Run Shell Script or Command On Remote With SSH Infografic
How To Run Shell Script or Command On Remote With SSH Infografic

LEARN MORE  Linux vs Unix

Leave a Comment