Execute a local sh file on a remote server over ssh

March 31, 2013

I wanted to automate running a deploy script on a few servers, just by running a command from my local command line. Executing a .sh file you have on your local filesystem on a remote computer, isn’t as easy as it looks. This is how i did it.

I run this line everytime i want to execute the script on the remote server (thanks to Yves for the updated version):

cat local-script.sh | ssh user@server "sed 's/{ctrl-v}{ctrl-m}//g' | bash"

What does this do:

cat local-script.sh
This just prints the local-script.sh file to the standardoutput. This file contains the script we want to execute on the server. In our case, the contents of the file gets piped to the next segment of the line by the pipe symbol (|)

ssh user@server
This part of the script creates an ssh connection to the server. This is pretty straightforward. When that’s done, everything between the double quotes (“) gets executed on the remote host.

sed 's/{ctrl-v}{ctrl-m}//g'
This part of the script converts carriage-returns into correct unix linefeeds. This is useful when you or someone in your team is working on a Windows machine.

| bash
Finally, it’s time to run the script, so we pipe (|) it to bash (the interpreter)

That’s it πŸ™‚

Advertisements

4 Responses to “Execute a local sh file on a remote server over ssh”

  1. yves Says:

    no need to store, chmod and execute the file… just use the magic pipes!

    cat local-script.sh | ssh user@server “sed ‘s/{ctrl-v}{ctrl-m}//g’ | bash”

    (assuming you’re using bash)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: