Run Single Remote Command via SSH on Ubuntu

Operating a remote Ubuntu Linux server often requires running quick commands without the need for a full, interactive terminal session. This article provides a straightforward guide on how to execute a single remote command via SSH, allowing you to automate tasks, query system status, and exit the connection automatically once the command finishes executing.

The Basic Syntax

To run a single command on a remote Ubuntu server without entering an interactive shell, append the command in quotes to the end of your standard SSH connection string:

ssh user@remote_host "command"

For example, to check the disk space on your remote server, run:

ssh sammy@192.168.1.50 "df -h"

Once the command executes, the output will print directly to your local terminal, and the SSH connection will immediately close.

Running Commands with Sudo Privileges

If the command you want to run requires administrative privileges (such as updating packages or restarting a service), you must allocate a pseudo-terminal. You can do this by adding the -t flag, which forces SSH to prompt you for your remote password:

ssh -t user@remote_host "sudo apt update"

Without the -t flag, the command will likely fail with a “sudo: no tty present and no askpass program specified” error.

Executing Multiple Commands Sequentially

You can chain multiple commands together within the same SSH session using standard shell operators like && (execute next if previous succeeds) or ; (execute next regardless of previous outcome):

ssh user@remote_host "cd /var/www/html && git pull"

Storing Output Locally

If you want to save the output of the remote command directly to a file on your local machine, use local redirection (>) outside of the quoted SSH command:

ssh user@remote_host "uptime" > local_uptime_log.txt