DevOpsLinuxOpen Source SoftwareTutorials

How to use sudo inside SSH command

Executing commands directly with SSH (without having to log in) is very easy. Just append the command you want to run on the target server at the end:

ck@linux:~$ ssh targetserver whoami
ck

ck@linux:~$ ssh targetserver uname -a
Linux targetserver 6.1.0-25-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.1.106-3 (2024-08-26) x86_64 GNU/Linux
running ssh command with sudo on remote server
running ssh command with sudo on remote server

However when you want to run a sudo command on the target server, you might get an error:

ck@linux:~$ ssh targetserver "sudo whoami"
sudo: a terminal is required to read the password; either use the -S option to read from standard input or configure an askpass helper
sudo: a password is required

The problem here is that the remote target server asks for a sudo password, but no TTY session was opened where the prompt for the password could be shown to.

To open a TTY session in the background, launch ssh with the -t parameter:

ck@linux:~$ ssh -t targetserver "sudo whoami"
[sudo] password for ck: ************
root
Connection to targetserver closed.

From the man page, the -t parameter is explained as pseudo-terminal. Since you're not actually logging into the remote target server with a "real" interactive session, but rather a "pseudo" session.

 -t      Force pseudo-terminal allocation.  This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services.  Multiple -t options force tty allocation, even if ssh has no local tty.

Claudio Kuenzler
Claudio has been writing way over 1000 articles on his own blog since 2008 already. He is fascinated by technology, especially Open Source Software. As a Senior Systems Engineer he has seen and solved a lot of problems - and writes about them.

You may also like

Leave a reply

Your email address will not be published. Required fields are marked *

More in:DevOps