How do I run a local bash script on remote machines via ssh?
You can pass a script and have it execute ephemerally by piping it in and executing a shell.
e.g.
echo "ls -l; echo 'Hello World'" | ssh me@myserver /bin/bash
Naturally, the "ls -l; echo 'Hello World'"
part could be replaced with a bash script stored in a file on the local machine.
e.g.
cat script.sh | ssh me@myserver /bin/bash
Cheers!
There are several ways to do it.
1:
ssh user@remote_server 'bash -s' < localfile
2:
cat localfile | ssh user@remote_server
3:
ssh user@remote_server "$(< localfile)"
number 3 is my prefered way, it allows interactive commands e.g. sudo -S service nginx restart
(#1 and #2 will consume the rest of the script as input for the password question when you use sudo -S
.)