How to use SSH to run a local shell script on a remote machine? How to use SSH to run a local shell script on a remote machine? shell shell

How to use SSH to run a local shell script on a remote machine?


If Machine A is a Windows box, you can use Plink (part of PuTTY) with the -m parameter, and it will execute the local script on the remote server.

plink root@MachineB -m local_script.sh

If Machine A is a Unix-based system, you can use:

ssh root@MachineB 'bash -s' < local_script.sh

You shouldn't have to copy the script to the remote server to run it.


This is an old question, and Jason's answer works fine, but I would like to add this:

ssh user@host <<'ENDSSH'#commands to run on remote hostENDSSH

This can also be used with su and commands which require user input. (note the ' escaped heredoc)

Edit: Since this answer keeps getting bits of traffic, i would add even more info to this wonderful use of heredoc:

You can nest commands with this syntax, and thats the only way nesting seems to work (in a sane way)

ssh user@host <<'ENDSSH'#commands to run on remote hostssh user@host2 <<'END2'# Another bunch of commands on another hostwall <<'ENDWALL'Error: Out of cheeseENDWALLftp ftp.secureftp-test.com <<'ENDFTP'testtestlsENDFTPEND2ENDSSH

You can actually have a conversation with some services like telnet, ftp, etc. But remember that heredoc just sends the stdin as text, it doesn't wait for response between lines

Edit: I just found out that you can indent the insides with tabs if you use <<-END !

ssh user@host <<-'ENDSSH'    #commands to run on remote host    ssh user@host2 <<-'END2'        # Another bunch of commands on another host        wall <<-'ENDWALL'            Error: Out of cheese        ENDWALL        ftp ftp.secureftp-test.com <<-'ENDFTP'            test            test            ls        ENDFTP    END2ENDSSH

(I think this should work)

Also seehttp://tldp.org/LDP/abs/html/here-docs.html


Also, don't forget to escape variables if you want to pick them up from the destination host.

This has caught me out in the past.

For example:

user@host> ssh user2@host2 "echo \$HOME"

prints out /home/user2

while

user@host> ssh user2@host2 "echo $HOME"

prints out /home/user

Another example:

user@host> ssh user2@host2 "echo hello world | awk '{print \$1}'"

prints out "hello" correctly.