Saturday, December 13, 2014

Execute script on remote server SSH - Unix

Assume you have a complex bash script named '' (containing good number of loops, Awk statements, multiple lines of code etc) that you need to run against one or more remote servers via SSH. One way would be to copy (i.e. scp) the script to the remote server(s) and then do something like this: e.g.
$ scp -2 root@

$ ssh -2 root@ sh /tmp/
If its multiple machines, then you can use bash for loop like this:
$ for ip in ; do echo "Executing on IP: $ip" ; ssh -2 root@$ip 'sh /tmp/' ; done
Now assume you do not want to copy your script to the remote machine(s) and want to execute from your local machine without copying it. Here's a way:
$ cat | ssh -2 root@ /bin/sh
And if its to be executed on multiple machines, you can use a for loop like this:
$ for ip in ; do echo "Executing on IP: $ip" ; cat | ssh -2 root@$ip /bin/sh ; done
I am sure you liked this trick ! Feel free to comment below. Thanks.

Related posts:

1 comment:

Allen Garvin said...

If you're putting it in a script and not just running it interactively, it can be a good idea to pass ssh a -n flag. There are situations when stdin needs to be read on the remote side, and without the flag, the script will have unexpected behavior (especially, when you're doing expect things on the other side). I tend to add it automatically when using ssh in any scripts.

© Jadu Saikia