/** * Gets the current user's group list from Unix by running the command 'groups' NOTE. For * non-existing user it will return EMPTY list. This method may return duplicate groups. * * @param user user name * @return the groups list that the {@code user} belongs to. The primary group is returned first */ public static List<String> getUnixGroups(String user) throws IOException { String result; List<String> groups = new ArrayList<>(); try { result = ShellUtils.execCommand(ShellUtils.getGroupsForUserCommand(user)); } catch (ExitCodeException e) { // if we didn't get the group - just return empty list LOG.warn("got exception trying to get groups for user " + user + ": " + e.getMessage()); return groups; } StringTokenizer tokenizer = new StringTokenizer(result, ShellUtils.TOKEN_SEPARATOR_REGEX); while (tokenizer.hasMoreTokens()) { groups.add(tokenizer.nextToken()); } return groups; }
private void setupShellMocks(String username, List<String> groups) throws IOException { PowerMockito.mockStatic(ShellUtils.class); String shellResult = ""; for (String group: groups) { shellResult = shellResult + " " + group; } PowerMockito.when( ShellUtils.execCommand(ShellUtils.getGroupsForUserCommand(Mockito.eq(username)))) .thenReturn(shellResult); }
/** * Tests the {@link ShellUtils#execCommand(String...)} method for a group of commands. * * @throws Throwable when the execution of the commands fails */ @Test public void execGetGroupCommand() throws Exception { String result = ShellUtils.execCommand(ShellUtils.getGroupsForUserCommand("root")); // On Linux user "root" will be a part of the group "root". On OSX it will be a part of "admin". Assert.assertTrue(result.contains("root") || result.contains("admin")); }
/** * Gets the current user's group list from Unix by running the command 'groups' NOTE. For * non-existing user it will return EMPTY list. This method may return duplicate groups. * * @param user user name * @return the groups list that the {@code user} belongs to. The primary group is returned first */ public static List<String> getUnixGroups(String user) throws IOException { String result; List<String> groups = new ArrayList<>(); try { result = ShellUtils.execCommand(ShellUtils.getGroupsForUserCommand(user)); } catch (ExitCodeException e) { // if we didn't get the group - just return empty list LOG.warn("got exception trying to get groups for user " + user + ": " + e.getMessage()); return groups; } StringTokenizer tokenizer = new StringTokenizer(result, ShellUtils.TOKEN_SEPARATOR_REGEX); while (tokenizer.hasMoreTokens()) { groups.add(tokenizer.nextToken()); } return groups; }