/** * Static method to execute a shell command. * Covers most of the simple cases without requiring the user to implement * the <code>Shell</code> interface. * @param cmd shell command to execute. * @return the output of the executed command. */ public static String execCommand(String ... cmd) throws IOException { return execCommand(null, cmd, 0L); }
/** * Static method to execute a shell command. * Covers most of the simple cases without requiring the user to implement * the <code>Shell</code> interface. * @param env the map of environment key=value * @param cmd shell command to execute. * @return the output of the executed command. */ public static String execCommand(Map<String,String> env, String ... cmd) throws IOException { return execCommand(env, cmd, 0L); }
/** * Get the current user's group list from Unix by running the command 'groups' * NOTE. For non-existing user it will return EMPTY list * @param user user name * @return the groups set that the <code>user</code> belongs to * @throws IOException if encounter any error when running the command */ private static Set<String> getUnixGroups(final String user) throws IOException { String result; try { result = ShellUtils.execCommand(ShellUtils.getGroupsForUserCommand(user)); } catch (ExitCodeException e) { // if we didn't get the group - just return empty list; LOG.debug("unable to get groups for user " + user + ".ShellUtils command failed with exit code "+ e.getExitCode()); return new HashSet<>(); } StringTokenizer tokenizer = new StringTokenizer(result, ShellUtils.TOKEN_SEPARATOR_REGEX); Set<String> groups = new HashSet<>(); while (tokenizer.hasMoreTokens()) { groups.add(tokenizer.nextToken()); } return groups; }
String resultFromMonitor = ShellUtils.execCommand(commands.toArray(new String[0]));