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

Hi, Have a need to run the below command as a "karuser" from a java class which will is running as "root" user. When we are trying to run the below command from java code getting the below error.

Command:

sudo -u karuser -s /bin/bash /bank/karunix/bin/build_cycles.sh

Error:

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

Your help will be much appreciated.

thanks

You can disable this requirement. Edit your sudoers file, locate the line

Defaults    requiretty

and disable it by putting a comment sign in front of the line.

Hi, Our system administrator informed that this ption can not be disabled due to security issues. Other than disabling 'requiretty' is there anyway to make this command work?

You have to create a pseudo terminal in one way or another. If you use ssh to connect for example, there is the -t option which does just that.

ssh -t hostname sudo ...

Does java offer a similar option?

The problem is not that it's asking for a tty. The problem is that it wants to ask for a password. That's why it wants a tty...

If sudo needs a password, then it needs a tty, sure.

But sudo also complains, when it doesn't need a password, because NOPASSWD is in effect. Just had that situation a few days ago. And the reason for this is the requiretty setting in the sudoers file afaik.

ssh user@host sudo.. -> complaint,

ssh -t user@host sudo... -> success without asking for a password,

removing requiretty and ssh user@host sudo.. -> success

It's an either-or thing, sure. It might require a TTY for either reason. But if it requires a password, you can get a confusing error about no TTY, because it needs a TTY to ask for a password...

You see similar things when ssh complains about not having an askpass program available. The error isn't actually the lack of an askpass program, of course; the error is that it needs to ask for a password and can't...

Manual seem pretty clear about requiretty:

No mention of password prompting here so it looks like you must be on a tty with this.

Note that the requiretty default requirement could be relaxed just for your particular script (/bank/karunix/bin/build_cycles.sh), so no need to open everything else up.

As to answer to the OP, I found an example on how to use ssh + sudo in java: JSch - Java Secure Channel - Examples Maybe this helps.