How to ssh to execute a command and exit?
If you want to execute a single command remotely and show the result on-screen and exit, this is a useful snippet ,
This will ssh to the remote hostname and execute your command mentioned between the quotes and continue the local prompt.
ssh username@hostname "your command"
Local server: devopsrun1
Remote server: devopsrun2
SSH passwordless authentication is enabled, so it is not prompting for a password. (You can read about ssh-key based authentication here: How to setup SSH-Key based authentication)
This can be used in shell scripts or loops where you are in need of sending a command or get details of multiple servers from one central server.
admin@devopsrun1~$ ssh admin@devopsrun2 "uptime"
15:57:57 up 2:49, 1 user, load average: 0.17, 0.16, 0.14
How to execute multiple commands on a remote server using ssh?
Another use case is to execute multiple commands on a remote server. You can enter multiple commands separated by semi-column.
Example for sending two commands, uptime and who -u is given below.
ssh username@hostname "command1 ; command2; command 3"
Hope this helps!
admin@devopsrun1~$ ssh admin@devopsrun2 "uptime;who -u"
X11 forwarding request failed on channel 0
16:03:11 up 2:54, 1 user, load average: 0.03, 0.09, 0.12
admin pts/0 2019-11-11 13:40 00:31 2552 (gateway)