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