Monday, July 27, 2009

Running Remote commands using SSH


Bookmark and Share



I found a very informative website discussing about how to run remote commands with SSH. Cool right?

It says there that it gets even cooler if you use SSH key-based authentication. That gives me an idea to summarize his discussion and also explain how to setup key-based authentication in ssh.

To run a remote command in ssh is pretty straight forward. Here is how you can do it:
# ssh remote_username@remote address 'remote_command' 

Example 1: To display the free disk space of your remote server

# ssh ruut@www.example.com 'df -h'
Filesystem Size Used Avail Use% Mounted on
/dev/ubda 3.5G 2.1G 1.4G 61% /
tmpfs 96M 4.0K 96M 1% /dev/shm

Example 2: To count the number of httpd process in your remote web server

# ssh ruut@www.example.com 'ps -ax | grep httpd | grep -v grep | wc -l'
11


The above examples will still prompt you to input the user's password if you still have not configured a key-based ssh authentication. Alright, I don't mind typing my password, after all it is there for security reasons. Why would I use the key-based authentication?

You will need this key-based authentication when for example you create a script that will execute a remote command regularly to monitor your remote sites. So you will configure your cron to do the job for you right?

Convinced now? Let me show you how to do it.

  1. Generate a private and public keys using ssh-keygen
    # ssh-keygen -t dsa -b 1024 

    To make this straight forward, just press the enter key when asked to enter a passphrase.
    This will create two files inside your
    /home/username/.ssh/
    directory:

    • id_dsa - your private key

    • id_dsa.pub - your public key



  2. Copy your public key securely to your remote site and place it inside /home/username/.ssh/ and name the file as authorized_keys
    # scp /home/username/.ssh/id_dsa.pub ruut@www.example.com:/home/ruut/.ssh/authorized_keys

  3. Now you can execute our Example 1 like to and it should not prompt you to input the password of your remote site account:
    # ssh -i /home/username/.ssh/id_dsa ruut@www.example.com 'df -h'




So that's how its done. I hope this article has help you in some ways.

Bookmark and Share

No comments:

Post a Comment