Monday, January 4, 2010

Execute multiple remote commands using SSH

Suppose you want to execute multiple commands on a remote server without going to that server and actually typing the commands there.

For instance you can get the pid of a process and then kill it using ssh as under:

ssh admin@remote << HEREDOC
KILLPID=`ps -ef | grep firefox | awk '{print $2}'`
kill -9 $KILLPID
HEREDOC

Explaination:

First of all, you need to know what a heredoc is. Using a heredoc also takes away the complexity associated with escaping special characters in a command (ticks and quotes in our example).

KILLPID=`ps -ef | grep firefox | awk '{print $2}'`

will define a shell variable KILLPID and assign PID of firefox process to it.

kill -9 $KILLPID

ofcourse we could have accomplished this using xargs but above example demonstrates how to remotely fire multiple commands in single SSH session.

In case you are curious how xargs would have served the purpose:

ssh admin@remote << HEREDOC
KILLPID=`ps -ef | grep firefox | awk '{print $2}' | xargs kill -9`
HEREDOC

Once we have the PID in a variable, we can kill it using kill -9 command

Happy SSHing.

No comments: