How to run commands on a remote machine using ssh(no interactive shell)

We all use ssh to access machines remotely, but not many know that instead of using a shell we can use ssh to simply run a command on the remote system. Just add the command, you want to be executed, after the user@host part and instead of throwing an interactive shell, ssh will run the command on the remote machine and show you the output(if any).

Here is a simple illustration:

[shredder12]$ ssh lucid@10.0.0.1 lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 10.04 LTS
Release: 10.04
Codename: lucid

If you want to run multiple commands, separate them with a semicolon, “;”.

[shredder12]$ ssh lucid@10.0.0.1 “lsb_release -a; ls”
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 10.04 LTS
Release: 10.04
Codename: lucid
file file1

Please note that, while using a semicolon(;) we need to use quotes, otherwise the semicolon will designate the end of complete ssh command. This will result in the command mentioned after it to run locally. Whatever is in the quote is executed as it is on the remote system. Hence, we can even use pipe or redirection. Quotes are required with them too.

[shredder12]$ ssh lucid@10.0.0.1 “lsb_release | grep \”10.04\”; ls > list”

Of course you’ll have to escape characters. The file “list” will be created on the remote server. This method is very useful when you want to execute a few commands on multiple systems. Pairing this with ssh key based authenticaton method(no password), a user's presence won't even be required once you execute the above command.

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <img> <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote> <h1> <h2> <h3> <h4> <h5> <h6> <p> <br>
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • Image links with 'rel="lightbox"' in the <a> tag will appear in a Lightbox when clicked on.

More information about formatting options

Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.