栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Java检查Linux用户的组成员身份

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Java检查Linux用户的组成员身份

您可以尝试读取文件

/etc/group

我开发了一个类来轻松查询此文件:

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;}

此代码映射

/etc/group
文件并保留其用户设置的组映射。我仅开发了一种查询方法(
belongs2group
),但是添加方法以列出所有组和/或所有用户非常容易。

这段代码是使用老式主流java io-api编写的,但我认为它可以轻松地适应nio。让我知道您是否需要我完成此步骤。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/405702.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号