Parker Smith Software

 
 

Remote execution of commands via SSH

By Brian Webb

2 Nov 2008

Often when we have a long list of commands that we need to run on a remote server we'll use Capistrano to do this. Especially if the tasks are related to a project and we'll be moving files to the server, creating directories, restarting processes etc. But what if the task to be completed on the remote server isn't that complex, maybe just a couple commands. In this application Capistrano seems a little overkill, but at the same time we don't want to login and execute the commands manually, there is a better way. Lets see how...

For this example we'll be running commands for an OpenSSH server, and we have a password-less login enabled through the use of public/private keys. Enough talk, how do we do it, well we start with the SSH command and some options

1
2

ssh -fCT user@domain.com pwd

Lets look at the options and what they mean:
-f = Tells SSH to close after the session is established
-C = Tells SSH to use compression
-T = Means that no terminal session will be started

So the above command will login to the remote server via SSH and execute the 'pwd' command and the output will be displayed in the terminal window. That is cool, but it is a pretty simple example, its not often that we are running 'pwd' remotely, additionally at Parker Smith for security we never run SSH on the default port 22. To do this we can expand the example a little more using some more SSH options.

1
2

ssh -fCT user@domain.com -p 29746 "mkdir /home/user/test; ps wax >> /home/user/test/processes.txt"

Now this example is a bit more complex and could be more adaptable to your situation. We are logging into SSH running on port 29746 and we quote the commands separated by a semicolon. This particular command will login to the server, make a directory called test in the user's home directory, then list some processes and write them into a text file within that directory.

To take this another step further you could pass a shell script as the last argument instead of a command, and the list of commands in the script will be executed. This is a little easier than trying to put all the commands in a string.

No Spam: 1 + 8 =