简体   繁体   中英

Check if a user is root in a java application

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 .

Easy. Just use

System.getProperty("user.name")

run a native command? like whoami

You can call

  Process p = Runtime.getRuntime.exec("whoami")

method. Then you can process p 's stdout to read output of command.

检查一下: 在java中获取登录用户名

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.

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 ie moderator but this user could be in root group and you have root privileges.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM