java获取linux用户,使用Java检查Linux用户的组成员身份

Hi I can't figure out how to verify if a user belong to one o more group under Linux os using java 7 nio library.

Can anyone help me about this issue?

解决方案

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 users = group2users.get(groupName);

if(users == null)

{

users = new HashSet();

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 groupRef = group2users.get(group);

if(groupRef == null) return false;

return groupRef.contains(user);

}

private String groupsFilePath = "/etc/group";

private Map> 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值