sudo requires a tty to read the password that you'll have to key in or it will throw the sudo: no tty present and no askpass program specified error such as when automating a script via ssh as in the following example;

$ ssh user@example.com -- sudo ls
user@example.com's password:
sudo: no tty present and no askpass program specified

These are a few methods to fix the issue as made apparent by the error description itself.

Method 1: Allocate tty

ssh has the option to allocate pseudo-terminal for each connection. It is however not set by default. You can force force pseudo-terminal allocation by using -t option when connecting.

-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 ser-
             vices.  Multiple -t options force tty allocation, even if ssh has no local tty.

Here's an example on how to use the option;

$ ssh -t user@example.com -- sudo id
user@example.com's password:
[sudo] password for user:
uid=0(root) gid=0(root) groups=0(root)
Connection to example.com closed.

Method 2: Install askpass

It's a method that I've not tried but should work. Will update this section once I've got my setup working.

Method 3: stdin sudo

You can force sudo to read the password from stdin by using stdin via -S switch such as in the following example;

$ ssh user@example.com -- sudo -S id
user@example.com's password:
[sudo] password for user: pass
uid=0(root) gid=0(root) groups=0(root)

Your password will be displayed on the stdout and could pose a securitk risk. pass is the password in this example.

Method 4: Passwordless sudo

This is to be set up on the remote machine that you're connecting to rather than on your local machine and is more like a workaround than a solution the the problem itself.

With this method you're only required to enter ssh user's password and will not be asked for password again for sudo.

$ ssh user@example.com -- sudo id
user@example.com's password:
uid=0(root) gid=0(root) groups=0(root)
Leave a comment:
Share!