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 ,
Code:
ssh username@hostname "your command"
Example:
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)
Code:
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.
Code:
ssh username@hostname "command1 ; command2; command 3"
Code:
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)