Check if a user is root in a java application

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

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

Thanks

7条回答
  •  暗喜
    暗喜 (楼主)
    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.

提交回复
热议问题