The SSH command can be used to remotely login to a server running an sshd daemon. This allows Linux administrators to perform variety of administrative jobs. However, SSH is more powerful than just providing a user with remote shell access, as it can also be used to automate remote command executions, like running simple backups and downloading the backup file locally.
In this guide, we’ll go over a few different command line examples to show how you can execute commands on a remote system via SSH, as well as direct the output back to your local machine.
In this tutorial you will learn:
- Examples for remote command execution via SSH
Category | Requirements, Conventions or Software Version Used |
---|---|
System | Any Linux distro |
Software | OpenSSH |
Other | Privileged access to your Linux system as root or via the sudo command. |
Conventions |
# – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command$ – requires given linux commands to be executed as a regular non-privileged user |
Examples for remote command execution via SSH
Use some of the commands below to see how remote command execution via SSH works, and adapt them to your own needs.
You can save yourself a step and avoid entering your SSH password every time you connect if you first follow our guide on SSH login without password.
- The following SSH command can be used to create a file remotely.
$ ssh user@hostname '( cd /tmp/ && touch ssh_file.txt )'
- This example will make a local copy of a remote
/etc/passwd
file to/tmp/passwd
:$ ssh user@username '( cat /etc/passwd )' > /tmp/passwd
- This example will execute a script on the remote server. Of course, this will only work if the script already exists and has the proper executable permissions.
$ ssh user@hostname '( cat ~/myscript.sh )'
- In this example we make a bzip2 local copy of the remote server’s
/var/log/auth.log
file to a local file in the/tmp/
directory:$ ssh user@hostname '( cp /var/log/auth.log /tmp/; cd /tmp/ && tar -jcvf - auth.log )' > /tmp/auth.tar.bz2
Closing Thoughts
In this guide, we saw how to use SSH to execute commands on a remote server with just a single command. We also learned how to redirect the output back to our local system, which can effectively let us use SSH to make quick backups, file transfers, or even execute scripts remotely. We have only scraped the surface here, and these commands can be adjusted to accomplish any kind of remote execution task that you come up with.