Run Remote Commands with SSH

October 25th, 2006

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:

root@admin:~ # ssh root@www '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.

root@admin:~ # ssh root@www 'ps -ef | grep apache | grep -v grep | wc -l'
11

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

root@www:~ # ssh root@www '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
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
 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:

root@www:~ # ssh root@www 'who'
brock pts/0 Oct 21 10:31 (75.72.194.149)
jim pts/1 Oct 25 06:25 (128.101.163.128)

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.

26 Responses to “Run Remote Commands with SSH”

  1. bash script to collect info - nixCraft Linux Forum Says:

    [...] quite easy to achieve (with pubkeys so you don’t have to enter passwords everytime). Run Remote Commands with SSH should get you started. However, there are much better tools for monitoring multiple boxes out [...]

  2. gravity_no_exception Says:

    hi….
    i used ssh to halt another user …after i entered thru ssh…. i entered the root …. then typed halt….
    the problem is that the system wont start….
    i cannt figure out why……
    please help me to start this system in normal mode…
    both systems have ubuntu(gutsy)

  3. David Says:

    Very helpful — thanks a lot for putting this up :)

  4. xozyain Says:

    “i used ssh to halt another user”
    how do you halt a user???
    you have probably have shut down your machine. push the power button. you can’t taht remotely. (unless it has WakeOnLAN, even then you need access to another machine in the same subnet)

  5. Setup SSH Keys to avoid password check « Kostas Mamalis blog Says:

    [...] install the key on a remote host. If the command below looks daunting, read the following articles Run Remote Commands with SSH and Standard Error and Standard Out . brock@www:~/.ssh$ cat id_rsa.pub | ssh mysql105 ‘cd [...]

  6. Prasanna Says:

    Hi,

    How can I run “ssh” command from Windows prompt to connect to the Server (solaris)?

    I mean, do I need to install any software to run SSH command in Windows command prompt and classpath settings required. Please suggest me… and can mail me to this ID as well (vaddamani.prasanna@yahoo.co.in)

    Regards,
    Prasanna

  7. John Says:

    I’d suggest doing:

    ssh root@www ‘ps -ef’ | grep apach[e]| wc -l’

    * Firstly, you connect, do a ps, then process the text on your machine

    * No need for “grep -v grep” by expanding one of the letters of what you’re grepping.

    - John

  8. Brock Noland Says:

    John,

    That’s a novel solution. Thanks for sharing!

  9. Moxy Says:

    Its gets much more interesting to start including ssh commands in scripts.I have a script which I run on one server which uses ssh to connect and execute scripts I have put on each of my 23 other servers.
    This basically takes the work out of my job.

  10. Sean Maloney Says:

    There’s also no need for the pipe to wc -l, its more efficient to use grep -c.

    So in effect:

    ssh root@www ‘ps -ef’ | grep -c apach[e]

  11. Manoj Says:

    How can i stop the execution of commands.
    for eg: if a user from system1 run a command like ssh user@system2 rm *, then it will delete all the files of the user in system.

    How can i stop the execution of commands through ssh.

  12. roger mormon Says:

    Another option is to put it all in a .sh file on the host and just run that.

  13. ceoph Says:

    To stop a rm * launch by another user by ssh user@system2 ‘rm *’
    Do ssh otheruser@system2 ‘ps aux | grep rm’ and otheruser@system2 ‘kill -9 pidnumberofrmcommand’

  14. Mish Says:

    I get prompted for a password when I use the sommands you showed.
    Suppose, I am running this from a script, I will I supply the password for the login in the script. Is there a command for that?

  15. ted cooper Says:

    this is how you ensure that that yes/no prompt won’t come up when you connect to a machine whose public key isn’t in the client’s ~/.ssh/known_hosts. you can dig this out of the ssh and ssh_config manpages, but I figured somebody might be looking for it:

    ssh root@www -o StrictHostKeyChecking=no ‘df -h’

  16. Robert M Parten II Says:

    The problem here is they forget to tell you one valuable piece of information…most systems ship by default with:

    permitrootlogin NO

    so if you were to use

    ssh root@192.168.15.120 ‘urpmi.update -a && urpmi –auto-select –auto’

    you will be asked for the root password; however, it will deny you access no matter how many times you put the correct password in.

    This is done for safety, for instance, if someone were to get your root password, they could execute something like this

    ssh root@192.168.15.120 ‘rm -rf –no-preserve-root /*’

    then your system is trashed.

    This is a nice feature, but plain old logging as a normal user and using either ’sudo’ or ’su -’ is more secure.

    Good luck

  17. neidisch Says:

    I would like to make a remote installation via ssh, for instance:

    neidisch@server1# ssh root@server2 /tmp/mysoftware/install

    it actually would work fine. except for the license that I have to agree: it’s displayed with “more” and can’t break it.

    if I use “ssh -n” it would work, but then I wouldn’t be able to pass my configuration values.

    can anyone help me?

  18. Execute shell script in different system - Shell Programming and Scripting - The UNIX and Linux Forums Says:

    [...] if it is a secure system then consider using SSH, take a look at: Run Remote Commands with SSH (to run commands remotely) and Setup the SSH server to use keys for authentication (to achieve [...]

  19. giro Says:

    How may I set or use a set JAVA_HOME environment ?

  20. Amit Verma Says:

    Hello Manoj,

    To stop some user to execute any command on a server (using SSH) you simply need to disable the sshd (ssh daemon) so that server. This way neither your server would be listening those remote SSH requests nor it would be processing them.

    Simple!


    Amit Verma

  21. Ian Vaughan Says:

    SSH with and without command gives different results? env is different?

    [a ~]$ ssh 172.24.40.100
    Last login: Mon Jan 1 06:07:24 2001 from 172.24.41.78
    [b ~]# /path/script.sh
    # works as expected

    [a ~]$ ssh 172.24.40.100 /path/script.sh
    # gives me error consistent with env setup

    Which implies the latter is running the script.sh on host a, when I want to ‘launch’ in from a, and ‘run’ it on b!?

  22. Brock Noland Says:

    Ian,

    When you login, your profile and rc scripts are called. You can call them in your script, to setup your environment. Or better yet, remove any dependencies on the environment being setup.

  23. vikrant Says:

    Hi,
    I need to execute a shell script on a remote machine. Without using ssh – how do i do it?
    the admin does not provide me ssh access. Is this possible?

    Please provide any valuable support.

    Thanks is advance.

  24. Brock Noland Says:

    vikrant,

    Are you provided ANY access to the server? If so, what? If not, this is not possible.

  25. Joe Says:

    How about replacing

    ssh root@www ‘ps -ef | grep apache | grep -v grep | wc -l’

    with pgrep -c apache

  26. Brock Noland Says:

    pgrep is not available everywhere, but yes you can use pgrep if available… The purpose of this article was ssh, not process listings.

    Please see my article which covers pgrep.

Leave a Reply

If Wordpress eats your comment (shell output, loops, ex..) email the text to me.