Tuesday, August 26, 2014

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

If you're trying to execute a command with "sudo" permission in a remote server using ssh, for example:

ssh user@remoteServer "sudo ls"

and get this error:
sudo: sorry, you must have a tty to run sudo

Then this means that the remote server doesn't allow arbitrary screen-based programs to run sudo on that server. there are several ways to work around this problem.

Using "-t" option:

You can use -t option to make your command work.
ssh user@remoteServer "sudo ls"

-t option enables arbitrary screen-based programs on a remote server.

Using "--session-command" option:

You can execute the command this way:

ssh user@remoteServer su --session-command="ls"

You can also use a specific user (for example "admin") to run the command in the remote server this way:

ssh user@remoteServer su --session-command="ls" admin

Changing the "requiretty" option in sudoers file in remote server:

The above were temporary solutions, if you want to have a more permanent solution then you must have the write access to /etc/sudoers file in the remote server.

You should see this line in /etc/sudoers file (in the remote server):

Defaults    requiretty

Comment out the line and save the file:

# Defaults    requiretty

If the "requiretty" option is set then "sudo" can only be run from a real tty (from a login session). Arbitrary logins or scripts cannot perform "sudo" with this option enabled. Commenting it out enables the arbitrary logins or scripts to perform "sudo".

For more info have a look at the page I learned this from:
http://www.cyberciti.biz/faq/linux-unix-bsd-sudo-sorry-you-must-haveattytorun/