Check if a user is root in a java application

前端 未结 7 739
日久生厌
日久生厌 2021-02-08 09:25

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

Thanks

相关标签:
7条回答
  • 2021-02-08 09:52
    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.

    0 讨论(0)
  • 2021-02-08 10:04

    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.

    0 讨论(0)
  • 2021-02-08 10:06

    Easy. Just use

    System.getProperty("user.name")
    
    0 讨论(0)
  • 2021-02-08 10:07
    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.

    0 讨论(0)
  • 2021-02-08 10:09

    Check this: get login username in java.

    0 讨论(0)
  • 2021-02-08 10:10

    You can call

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

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

    0 讨论(0)
提交回复
热议问题