Strovent SystemsSign in
Reference

sudo "a terminal is required to read the password" when running a command over SSH

ssh host sudo command runs without a terminal, so sudo cannot ask for the password. Add ssh -t, or set up a sudoers rule or askpass for scripts.

You run a command with sudo on a remote host in one go:

$ ssh [email protected] sudo systemctl restart nginx
sudo: a terminal is required to read the password; either use ssh's -t option or configure an askpass helper

Older sudo versions say sudo: no tty present and no askpass program specified for the same thing.

Why

When you give ssh a command, it runs it without a terminal on the host unless you ask for one. sudo reads your password from the terminal so that it can turn off echo while you type. With no terminal, and no askpass helper, it has nowhere to ask and stops.

sudo picks the wording from its environment: when SSH_CONNECTION is set but SSH_TTY is not, it suggests ssh's -t. Otherwise it suggests its own -S option.

Interactive use: ssh -t

ssh -t [email protected] sudo systemctl restart nginx

-t makes ssh allocate a terminal on the host, so sudo can prompt as usual. Use it when you are at the keyboard. If ssh itself has no local terminal, for example when your command is run from a script, give -tt to force one.

Scripts and automation

A script cannot type a password at a prompt, so pick one of these instead:

  • A sudoers rule for exactly that command, with NOPASSWD, added by the administrator with visudo. Then sudo -n (non-interactive) runs it without prompting, and fails at once instead of waiting if a password would be needed.
  • An askpass helper: a program that prints the password, named in SUDO_ASKPASS and used with sudo -A.
  • sudo -S, which writes the prompt to standard error and reads the password from standard input instead of the terminal.

sudo -n failing with sudo: a password is required tells you that the rule you expected does not match the command.

Same message with SFTP

SFTP has no terminal either, so starting the SFTP server through sudo hits the same message. See SFTP with sudo: edit root-owned files with sftp -s.

Sources

Spotted a mistake? Email [email protected].