How to Run or Execute Remote Linux Commands over SSH

Published July 05, 2024

Run / Execute Linux commands on a remote server over SSH How to run or execute remote Linux commands on a remote server over SSH

Sometimes, you may need to ssh into a remote Linux server, run a single command or couple of commands and log out. To do this without making it a 3 step process, you can ssh to the server. run the command and automatically log outin one line.

Find hostname of the server the usual way

Your traditional way of doing this is:

  1. ssh to the server
  2. Run hostname
  3. Log out

Let us say my server is called devbox, and I login as user arul.

ssh arul@devbox
hostname

And then, press control+D to logout.

Find hostname of the server using a single ssh command

The shortcut way of doing this is:

ssh arul@devbox 'hostname'

This command will log you into the box, run hostname command, print the results and automatically log out.

Run bash aliases over ssh

If you have an alias, and you want to run it in bash on the remote server, you have to do it in a different way.

If the alias name is findtemps and it runs a bunch of tasks, this is how you call it over ssh.

ssh arul@devbox bash -ic 'findtemps'

Running this will execute the bash alias findtemps over ssh.

Run multiple commands over ssh

To run date as well as hostname over ssh, separate the commands with a semicolon ;

ssh arul@devbox 'date ; hostname'

Run script on remote server over ssh

To run a script /user/local/bin/daily_backup.sh over ssh, just call it.

ssh arul@devbox '/user/local/bin/daily_backup.sh'

Run script on remote server using sudo over ssh

To run a script /user/local/bin/daily_backup.sh over ssh using sudo:

ssh arul@devbox 'sudo /user/local/bin/daily_backup.sh'

Run multiple commands in a local file over remote Linux server over ssh

If you have a local file daily_commands.txt with these commands:

hostname
date
df -h

And you want to run all the commands in that file over ssh:

ssh arul@devbox < daily_commands.txt

Run multiple ssh commands from within a shell script

If you have a shell script run_daily.sh and you want to run multiple remote programs over ssh, use ssh -T with HEREDOC:

#!/bin/bash

ssh -T arul@devbox <<"EOL"
    hostname
    date
    df -h
EOL

Conclusion

If this worked for you or did not work for you, do let me know. Thanks.

Related Posts

If you have any questions, please contact me at arulbOsutkNiqlzziyties@gNqmaizl.bkcom. You can also post questions in our Facebook group. Thank you.

Disclaimer: Our website is supported by our users. We sometimes earn affiliate links when you click through the affiliate links on our website.

Last Updated: July 05, 2024.     This post was originally written on July 05, 2024.