How can i verify if a user is root in a java application?
Thanks
Process p = Runtime.getRuntime().exec("id -u")
Keep in mind that the "root" user on a system may not be called root
(although it's rare to change it), and it's also possible to alias it to another username. If the current user is root-like, the output will be 0
.
The best way is to run
Process p = Runtime.getRuntime.exec("groups `whoaim`");
and try to parse string to get group call root. Your JVM process could be run by user not call root but i.e. moderator but this user could be in root group and you have root privileges.
Easy. Just use
System.getProperty("user.name")
String userName = System.getProperty("user.name");
Process p = Runtime.getRuntime().exec("groups " + userName);
String output = read(p.getInputStream());
String error = read(p.getErrorStream());
And here is a read function:
public static String read(InputStream input) throws IOException {
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) {
return buffer.lines().collect(Collectors.joining("\n"));
}
}
Just "another" modified solution.
Check this: get login username in java.
You can call
Process p = Runtime.getRuntime.exec("whoami")
method. Then you can process p's stdout to read output of command.