Check if a user is root in a java application

梦想与她 提交于 2020-01-22 12:04:24

问题


How can i verify if a user is root in a java application?

Thanks


回答1:


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.




回答2:


Easy. Just use

System.getProperty("user.name")



回答3:


run a native command? like whoami




回答4:


You can call

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

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




回答5:


Check this: get login username in java.




回答6:


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.




回答7:


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.



来源:https://stackoverflow.com/questions/5117449/check-if-a-user-is-root-in-a-java-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!