Execute remote command using ssh

How to

If is needed to execute command or script on a remote UNIX based machine using ssh program is the best way how to do it. Ssh provides secure encrypted communications between two untrusted hosts over an insecure network.

For this example you need to have configured ssh public keys over hosts you need to execute commands. you can find articel which covers this here: Using a SSH Key-Based Authentication.

For simple command.

ssh remotehost hostname

 

When we need to execute more than one command.

ssh remotehost "hostname; date"

 

Another example how to use it is piping it in and executing a shell.

echo "hostname; date" | ssh remotehost /bin/sh

 

Or we can use variable variable.

FS="/var"; ssh remotehost "df -k $FS"

 

This is an example how to run local script on remote host.

ssh remotehost  'bash -s' < local_script.sh

 

Or with piping

cat local_script.sh | ssh storage2 /bin/bash

 

This is an example how to combine inline remote commands with passing ENV variables from the local machine to the remote host so you can parameterize your scripts on the remote side.

ssh storage2 'ARG1=ARG1 ARG2=ARG2' 'bash -s' << 'ENDSSH'
echo $ARG1 $ARG2
ENDSSH

 

At the end, we can use “for” loop and execute command on several hosts just with one line.

for host in `cat list_of_hosts.txt`; do ssh $host uptime; done

Leave a Reply