Learn the UNIX/Linux command line

Run Remote Commands with SSH

The ssh command is an amazing program. You can use it for opening sessions between server or you can use it run a command on a remote system, non-interactively. A simple example of which might be getting file system usage:

[email protected]:~ # ssh [email protected] '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

This is cool, but is not extremely useful. It gets really cool when you use SSH public/private key pairs to automate tasks on many servers. I will cover that in the future.

Until then, you can still do some pretty cool stuff, like count the number of webserver proccess running on your webserver. Without actually logging into the box and typing the command. All you have to do is place the command in quotes after the base ssh command. The following connects to the server www as root and then pipes the process table to grep apache. It then pipes that to grep -v grep (this eliminates the process grep apache itself and leaves the apache processes) and finally to wc -l which counts the number of lines, in this case the number of apache processes.

[email protected]:~ # ssh [email protected] 'ps -ef | grep apache | grep -v grep | wc -l'

Or display a systems vital stats and highest CPU utilizing process:

[email protected]:~ # ssh [email protected] 'top -b -n 1 | head -n 8'
top - 11:01:04 up 20 days, 6:47, 1 user, load average: 0.44, 0.21, 0.09
Tasks: 60 total, 1 running, 59 sleeping, 0 stopped, 0 zombie
Cpu(s): 1.7% user, 1.5% system, 0.0% nice, 96.8% idle
Mem: 195620k total, 186276k used, 9344k free, 16380k buffers
Swap: 525304k total, 516k used, 524788k free, 26912k cached
7399 root 19 0 936 936 740 R 9.2 0.5 0:00.20 top
Or see who is logged in on a system:
[email protected]:~ # ssh [email protected] 'who'
brock pts/0 Oct 21 10:31 (
jim pts/1 Oct 25 06:25 (

If you would like to be even more amazed or amused read my article on setting up ssh keys. SSH keys allow you to
skip entering a password, like I did above, when running commands on remote systems.