Run command on remote server via ssh

If you need to run a command or shell script on a remote server via ssh

Syntax

ssh <username>@<hostname> '<commands>'
             ssh command uses three mandatory input, 
             username = username to login to remote system
             hostname = Remote system name or ip address
             commands = single command or list of commands seperated by semicolon

Command will login to remote system with the provided username and password and executes the listed command and retrives the return data and shows in terminal or you can redirected to a file using redirect sysmbol.

Instead of execute a command, you can also execute a shell script or any executable remotely.

Exmples:

ssh user@system1 'ls -l'

above command will execute the ls command in home folder of the user and returns a long list of file lists available.

ssh user@system 'pwd; ls; whoami'

above command will execute the commands one by one.

pwd - current directory - home directory of the logged user, ls - list files in home directory, whoami - shows the current logged in user name.

Executing a remote shell script or a executable

ssh -t user@remotesystem 'sudo service mysql restart'

To start or to stop a service or executable with sudo user access we need to use -t option to Force pseudo-terminal allocation.

-t Force pseudo-terminal allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful,

e.g. when implementing menu services. Multiple -t options force tty allocation, even if ssh has no local tty.

Facebook Facebook Twitter Reddit

Leave a Reply