Check group membership for a Linux user using Java

爷,独闯天下 提交于 2019-11-28 02:22:17

You can try to read the file /etc/group.

I have developed a class to easily query this file:

public class UserInfo {

    public UserInfo() throws FileNotFoundException, IOException {
        this.group2users = new HashMap<>();

        FileReader fileReader = new FileReader(groupsFilePath);
        BufferedReader groupsReader = new BufferedReader(fileReader);
        while(groupsReader.ready())
        {
            try
            {
                String line = groupsReader.readLine();
                String [] tokens = line.split(":");
                String groupName = tokens[0];
                Set<String> users = group2users.get(groupName);
                if(users == null)
                {
                    users = new HashSet<String>();
                    group2users.put(groupName, users);
                }
                if(tokens.length>3)
                {
                    for(String uStr: tokens[3].split(","))
                        users.add(uStr);
                }
            } catch (Exception e) { continue; }
        }
        groupsReader.close();
        fileReader.close();
    }

    public boolean belongs2group(String user, String group)
    {
        Set<String> groupRef = group2users.get(group);
        if(groupRef == null) return false;
        return groupRef.contains(user);
    }

    private String groupsFilePath = "/etc/group";
    private Map<String, Set<String>> group2users;

}

This code maps the /etc/group file and keep a map of groups-their users set. I have developed just one query method (belongs2group) but it is fairly easy to add methods to list all groups and/or all users.

This code is written using the old-fashioned-mainstream java io-api but I think it can be easily adapted to nio. Let me know if you need me to complete that step.

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