sorry, you must have a tty to run sudo

I don't know how to run shell commands in Java but have a look at -t option for ssh command

-t force pseudo-tty allocation.

That is what I do when I need to run command as root over ssh(direct root login disable and tty required by sudo)


My Question is, is it possible to execute my above command in java without making any changes anywhere i.e. by having default settings?

sudo -u -S pwd

The short answer is no, you will need to change settings to get sudo to do things differently than it currently does.

sudo may be the wrong tool for this. Sudo's rules are there to help system administrators configure a way to gain elevate privileges that is difficult to abuse to get additional/unintended privileges.

If you consider what sudo does for you:

  1. prompts for password to verify identity
  2. elevate privileges
  3. then optionally get privileges as another user
  4. logs sudo use to gain access or run commands

If you want your java to run arbitrary commands as arbitrary users without providing password for either those users or your own you are essentially replacing sudo. In that case you should create your own rules for how to prevent abuse.

There are basically two ways to do this:

  1. run your java with elevated privileges and carefully take and give back privileges you need (see setuid() seteuid() C function calls).
  2. run an external program to grab elevated privileges when you want them

In the case of #1 your java program is performing itself what sudo does, and you should implement your own set of rules to protect from abuse.

There are programs other than sudo to do #2. One example can be found in https://code.google.com/archive/p/exec-wrapper/downloads

This handy shell script creates a C program to run another command (usually a script). Then you compile the C program to a binary and mark that setuid root or really it could be setuid to any user. (mode :4555 and owner: root)

As long as you are on a filesystem that allows it, running the binary program will run the configured command as the userid that owns the binary program itself.