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.

  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/  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 | ssh -i /home/naishe/.keys/remotekey.pem \ "cat > /tmp/ ; chmod 755 /tmp/ ; \
/tmp/ param1 param2 ; rm -f /tp/ " 

You see, it's pretty simple.