Commands.page Logo

How to Run Sudo Commands on Remote Ubuntu Via SSH

Yes, you can use sudo to execute privileged commands on a remote Ubuntu machine through SSH. This article explains the correct syntax for combining sudo and SSH, how to handle password prompts efficiently, and the necessary configuration changes required in the sudoers file to enable passwordless execution for automation. By following these steps, you can securely manage remote systems without logging into an interactive shell.

Basic Command Syntax

To run a command with sudo privileges on a remote host, you simply prepend sudo to the command within the SSH quotation marks. The standard format looks like this:

ssh user@remote_host "sudo your_command"

When you run this, SSH connects to the remote machine, and the remote shell attempts to execute the command with elevated privileges. If the user account requires a password for sudo, you will be prompted to enter it after the SSH connection is established.

Handling Password Prompts

By default, sudo requires a terminal (TTY) to accept password input securely. Standard SSH commands may not allocate a pseudo-terminal, causing sudo to fail with a “no tty present” error. To fix this, add the -t flag to your SSH command to force TTY allocation:

ssh -t user@remote_host "sudo your_command"

This ensures that the password prompt displays correctly and accepts your input. However, this method still requires manual interaction, which is not suitable for automated scripts.

Configuring Passwordless Sudo

For automation, you can configure the remote Ubuntu machine to allow specific commands or users to run sudo without a password. This is done by editing the sudoers file using the visudo command on the remote machine:

sudo visudo

Add the following line to the end of the file, replacing username with your actual remote user:

username ALL=(ALL) NOPASSWD: ALL

For better security, you can restrict this to specific commands instead of allowing all commands. Once saved, your SSH sudo commands will execute without prompting for a password.

Security Best Practices

Enabling passwordless sudo reduces security barriers, so it should be done cautiously. Never disable password requirements for the root user globally. Instead, grant NOPASSWD privileges only to specific service accounts or restrict the permission to only the specific commands required for your task. Always ensure your SSH keys are secure and protected with a passphrase to prevent unauthorized access to the remote machine.