sudo: sorry, you must have a tty to run sudo

Shell Tips
September 8, 2014 | COMMENTS

You just have configured your sudoers to execute some command without password from a ssh connection. Bummer, you just got an error:

sudo: sorry, you must have a tty to run sudo

No panic, there is an easy fix! It is most-likely that you are running on a Linux distribution with sudo configured to require a tty. This is generally enforced by having Defaults requiretty in the /etc/sudoers.

Some Linux distributions have been known to have this as a default configuration. RedHat just recently removed this from Fedora and REHL, see Bug 1020147.

What is the fix?

To disable requiretty globally or to a single command, you have two options:

  1. Replace Defaults requiretty by Defaults !requiretty in your /etc/sudoers. This will impact your global sudo configuration.

Alternatively, you can change this configuration at a per user, per group or per command basis

Defaults!/path/to/my/bin !requiretty
Defaults:myuser !requiretty
  1. Connect by ssh using -t options

From man ssh:

     -t      Force pseudo-tty 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.