SSH tip: Send commands remotely
If needed you can run SSH commands followed by immediately logging out of the remote system.
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:
- Run the command "ssh username@host" to log in to the system
- At the command prompt, run "top" to view process activity on the remote system
- Exit top and be dropped to the remote command line
- 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.
This method of issuing commands is convenient, especially if you would like to run a command that takes a while to execute, but don't wish to stay around and wait for it to finish, as might be the case with a backup script. If you run the command this way, when finished the system will drop you back to your local machine and close the remote connection.