SSH Send remote command

When connecting to a system remotely using SSH (Secure Shell), usually you provide the SSH command string to log in to the system and then execute commands on the remote system using the current SSH session. This is the standard behavior and is good for performing system management tasks that take more than just a few steps, but sometimes you might only need to log in and run a single specific command or script.

For example, if you would like to check a Mac’s process activity by using the “top” command, you would perform the following steps in the Terminal:

  1. Run the command “ssh username@host” to log in to the system
  2. At the command prompt, run “top” to view process activity on the remote system
  3. Exit top and be dropped to the remote command line
  4. Type “Exit” to close the command

This approach is easy enough, but you can also combine these two commands so the SSH session will log in and run the specified command, and then exit so it will not maintain a connection with the remote server. To do this, simply provide the command in quotes following the ssh log-in command, and provide the “-t” flag to ensure proper interaction with the remote system is allowed, if needed:

ssh -t username@host ‘top’

If you need to perform multiple commands, you can do so by separating them with semicolons in the command string. Since sudo is often used when running commands in the Terminal, be sure you include the “-t” flag as shown in the command above, otherwise you will not be able to provide the administrative password to the remote system when prompted and it will be shown in the Terminal when typed instead of masked. The “-t” flag is also required if you intend to run commands that require more interaction,such as “top” or similar monitoring services. Without this flag, these commands will output an ever-growing string to the Terminal as they update their output.