How to run a script file remotely using SSH

ScriptingSsh

Scripting Problem Overview


I want to run a script remotely. But the system doesn't recognize the path. It complains that "no such file or directory". Am I using it right?

ssh kev@server1 `./test/foo.sh`

Scripting Solutions


Solution 1 - Scripting

You can do:

ssh user@host 'bash -s' < /path/script.sh

Solution 2 - Scripting

Backticks will run the command on the local shell and put the results on the command line. What you're saying is 'execute ./test/foo.sh and then pass the output as if I'd typed it on the commandline here'.

Try the following command, and make sure that thats the path from your home directory on the remote computer to your script.

ssh kev@server1 './test/foo.sh'

Also, the script has to be on the remote computer. What this does is essentially log you into the remote computer with the listed command as your shell. You can't run a local script on a remote computer like this (unless theres some fun trick I don't know).

Solution 3 - Scripting

If you want to execute a local script remotely without saving that script remotely you can do it like this:

cat local_script.sh | ssh user@remotehost 'bash -'

It works like a charm for me.

I do that even from Windows to Linux given that you have MSYS installed on your Windows computer.

Solution 4 - Scripting

I don't know if it's possible to run it just like that.

I usually first copy it with scp and then log in to run it.

scp foo.sh user@host:~
ssh user@host
./foo.sh

Solution 5 - Scripting

Make the script executable by the user "Kev" and then remove the try it running through the command sh kev@server1 /test/foo.sh

Solution 6 - Scripting

I was able to invoke a shell script using this command:

ssh ${serverhost} "./sh/checkScript.ksh"

Of course, checkScript.ksh must exist in the $HOME/sh directory.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionProgress ProgrammerView Question on Stackoverflow
Solution 1 - ScriptingGerman AttanasioView Answer on Stackoverflow
Solution 2 - ScriptingpsanfView Answer on Stackoverflow
Solution 3 - ScriptingSergey KuznetsovView Answer on Stackoverflow
Solution 4 - ScriptingMacarseView Answer on Stackoverflow
Solution 5 - ScriptingMilind JindalView Answer on Stackoverflow
Solution 6 - ScriptingAmit SinghView Answer on Stackoverflow