What’s the Point?
Executing commands is one of the core tenants of computing. Sometimes, th desire to execute a command on a remove machine arises. Think ‘hey remote computer, run updates’ or ‘wake up office computer, I need a file’. Remotely connecting to, and executing commands on, remote machines is imperative to computing. Even more so the internet net activities. In this article we review how to connect via SSH (Secure Shell) to a Linux (or Unix) remote machine and run a command.
- Side note, this article does NOT cover how to setup public/private key pairs, shell account creation, etc. The focus centrally how to pass a a command via SSH to a remote machine.
Requirements
- Basic terminal usage
- Linux local machine (or WSL for you Windows people)
- SSH client on local machine, SSH server on remote machine (OpenSSH is a popular one)
Process
Open up a terminal…
Type the ssh connection command to ensure we have access
ssh -i ./.ssh/my-key.pem ubuntu@54.147.254.33
Ok, looks like we can connect successfully. Lets exit now in preparation for the next step.
exit [PRESS ENTER]
Now let’s wrap a ‘Hello World’ echo command inside the SSH execution.
ssh -i ./.ssh/my-key.pem ubuntu@54.147.254.33 'echo "Hello World"'
Look at that! The command executed on the remote machine. To prove it press the up arrow on your keyboard. You will notice the most recent command is not ‘echo “Hello World”‘, rather the parent SSH command just executed. To double check this, lets create a file on the remote machine, then log in to see if it is indeed present.
…and it is present! Nice.
Conclusion
Yes, it really is that simple. Being so simple, and knowing the ability exists, what are some of the possible uses you can think of? Do you know of a process that requires manual steps on a remote machine to complete? If so, here si the key to making a time consuming process a one line command.
Additional Resources
- https://en.wikipedia.org/wiki/Secure_Shell
- https://stackoverflow.com/questions/18502945/how-to-execute-a-remote-command-over-ssh-with-arguments
- https://askubuntu.com/questions/282319/how-to-use-sshpass
- https://www.cyberciti.biz/faq/noninteractive-shell-script-ssh-password-provider/
- https://www.cyberciti.biz/faq/linux-unix-osx-bsd-ssh-run-command-on-remote-machine-server/