Friday, August 3, 2012

Running Shell Script on Remote Machine

Motivation: Most of the time running a command or a group of commands on a remote machine is a thoughtless process -- ssh username@remoteIP.or.dns "command1 param1 param2; command2 param3;". What throws you out is when you have 40 lines of convoluted script to be run on 37 machines! You won't use this approach. You'd probably scp the script to remote machine and then call it using ssh as mentioned earlier, and then probably delete this file. It's three step process. If you haven't automated stuff, it's a pain.

A better way is to automate this process and do it in a single connection.

Prerequisites:
  1. Executable access to the remote machine.
  2. Some knowledge of shell script.
Steps: It's just one line command. I will write the breakdown.
  1. Keep the shell script that you wanted to execute remotely, on your local machine. cat this file.
  2. The cated file is piped to ssh command that...
  3. Writes this file to a location of your choice on remote machine, say /tmp/remote.sh  and...
  4. Changes mode chmod to executable then...
  5. Calls this script with parameters, if any, and finally...
  6. Deletes this file from remote location. 
The most interesting part is that all this is done in a single connection. Here is the code. The \ is continue command to next line. You may want to keep the whole command in a single line.

cat runremote.sh | ssh -i /home/naishe/.keys/remotekey.pem \
root@server1.naishe.in "cat > /tmp/remote.sh ; chmod 755 /tmp/remote.sh ; \
/tmp/remote.sh param1 param2 ; rm -f /tp/remote.sh " 

You see, it's pretty simple.

2 comments: