用户和用户组,以及文件和文件夹的权限
Authenticated Users
System
Administrators
Users
假如一个用户属于2个用户组的话,deny的优先级更高
log在写文件的时候,如果没有权限访问。会遇到UnauthorizedAccessException,这个异常需要直接抛出到顶层
获取当前用户
Console.WriteLine(WindowsIdentity.GetCurrent().Name);
Console.WriteLine(Environment.UserName);
Console.WriteLine(Environment.UserDomainName);
获取当前用户属于哪些用户组
方法1 只能获取20个用户 GetGroups
var userName = "clu"; var domainName = "asnet"; PrincipalContext principalContext = new PrincipalContext(ContextType.Domain,domainName); var userPrincipal = UserPrincipal.FindByIdentity(principalContext, userName); List<string> result=new List<string>(); if (userPrincipal != null) { var groups = userPrincipal.GetGroups(); foreach (Principal item in groups) { if (item is GroupPrincipal) { result.Add($@"GroupName = {item.Name}, DisplayName = {item.DisplayName}, Description = {item.Description}, Guid = {item.Guid}"); } } } Console.WriteLine($@"GroupCount = {result.Count}"); foreach (var item in result) { Console.WriteLine(item); }
GroupCount = 20
GroupName = SYG - ISC RDC, DisplayName = SYG - ISC RDC, Description = , Guid = 599392b2-cc8b-4e9e-8a6d-ff01539946d9
方法2 可以获取104个用户组 GetAuthorizationGroups
var userName = "clu"; var domainName = "asnet"; PrincipalContext principalContext = new PrincipalContext(ContextType.Domain,domainName); var userPrincipal = UserPrincipal.FindByIdentity(principalContext, userName); List<string> result=new List<string>(); if (userPrincipal != null) { var groups = userPrincipal.GetAuthorizationGroups(); foreach (Principal item in groups) { if (item is GroupPrincipal) { result.Add($@"GroupName = {item.Name}, DisplayName = {item.DisplayName}, Description = {item.Description}, Guid = {item.Guid}"); } } } Console.WriteLine($@"GroupCount = {result.Count}"); foreach (var item in result) { Console.WriteLine(item); }
GroupCount = 104
方法3 据说可以获取nested groups,虽然获取到的也是104个用户组
GetAuthorizationGroups()
does not find nested groups. To really get all groups a given user is a member of (including nested groups), try this:
List<string> result = new List<string>(); WindowsIdentity wi = new WindowsIdentity("clu"); foreach (IdentityReference group in wi.Groups) { try { result.Add(group.Translate(typeof(NTAccount)).ToString()); } catch (Exception ex) { } } result.Sort(); Console.WriteLine($@"GroupCount = {result.Count}"); foreach (var item in result) { Console.WriteLine(item); }
方法4 这个方法只能获取19个用户组
First of all, GetAuthorizationGroups() is a great function but unfortunately has 2 disadvantages:
- Performance is poor, especially in big company's with many users and groups. It fetches a lot more data then you actually need and does a server call for each loop iteration in the result
- It contains bugs which can cause your application to stop working 'some day' when groups and users are evolving. Microsoft recognized the issue and is related with some SID's. The error you'll get is "An error occurred while enumerating the groups"
Therefore, I've wrote a small function to replace GetAuthorizationGroups() with better performance and error-safe. It does only 1 LDAP call with a query using indexed fields. It can be easily extended if you need more properties than only the group names ("cn" property).
最后一句看不懂,cn property不知道是干嘛的
var userName = "clu"; var domainName = "asnet"; var result = new List<string>(); if (userName.Contains('\\') || userName.Contains('/')) { domainName = userName.Split(new char[] { '\\', '/' })[0]; userName = userName.Split(new char[] { '\\', '/' })[1]; } using (PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domainName)) using (UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, userName)) using (var searcher = new DirectorySearcher(new DirectoryEntry("LDAP://" + domainContext.Name))) { searcher.Filter = String.Format("(&(objectCategory=group)(member={0}))", user.DistinguishedName); searcher.SearchScope = SearchScope.Subtree; searcher.PropertiesToLoad.Add("cn"); foreach (SearchResult entry in searcher.FindAll()) if (entry.Properties.Contains("cn")) result.Add(entry.Properties["cn"][0].ToString()); } Console.WriteLine($@"GroupCount = {result.Count}"); foreach (var item in result) { Console.WriteLine(item); }
方法5 更快的方法 只获取了98个用户组
DirectorySearcher ds = new DirectorySearcher(); ds.Filter = String.Format("(&(objectClass=user)(sAMAccountName={0}))", @"clu"); SearchResult sr = ds.FindOne(); DirectoryEntry user = sr.GetDirectoryEntry(); user.RefreshCache(new string[] { "tokenGroups" }); var result = new List<string>(); for (int i = 0; i < user.Properties["tokenGroups"].Count; i++) { SecurityIdentifier sid = new SecurityIdentifier((byte[])user.Properties["tokenGroups"][i], 0); NTAccount nt = (NTAccount)sid.Translate(typeof(NTAccount)); //do something with the SID or name (nt.Value) result.Add(nt.Value); } Console.WriteLine($@"GroupCount = {result.Count}"); foreach (var item in result) { Console.WriteLine(item); }
获取指定的用户组有哪些用户
var domainName = "asnet"; var groupName = "SYG - ISC RDC"; PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domainName); var groupPrincipal = GroupPrincipal.FindByIdentity(principalContext, groupName); List<string> result = new List<string>(); if (groupPrincipal != null) { var users = groupPrincipal.GetMembers(true); foreach (UserPrincipal user in users) { result.Add( $"EmployeeId = {user.EmployeeId}, {user.DisplayName}, {user.EmailAddress}, {user.GivenName}, {user.MiddleName}, {user.Surname}"); } } else { Console.WriteLine($@"Can not find user group named as {groupName}"); } Console.WriteLine($@"UserCount = {result.Count}"); foreach (var item in result) { Console.WriteLine(item); }
获取用户是否有某一个文件的写权限
string path = @"D:\ChuckLu\Git\Edenred\LISA_5.0.0.0\LISA.ControlPanel\LISA.ControlPanel\bin\Debug\log\20171206.0.log"; string NtAccountName = @"asnet\clu"; FileInfo fileInfo = new FileInfo(path); var fileSecurity = fileInfo.GetAccessControl(); var authorizationRuleCollection = fileSecurity.GetAccessRules(true, true, typeof(NTAccount)); foreach (AuthorizationRule item in authorizationRuleCollection) { Console.WriteLine(item.IdentityReference); if (item.IdentityReference.Value.Equals(NtAccountName, StringComparison.OrdinalIgnoreCase)) { var item1 = item as FileSystemAccessRule; if (item1 != null) { if ((item1.FileSystemRights & FileSystemRights.WriteData) > 0) { Console.WriteLine(string.Format("{0} has write access to {1}", NtAccountName, path)); } else { Console.WriteLine(string.Format("{0} does not have write access to {1}", NtAccountName, path)); } } else { Console.WriteLine($@"{item.IdentityReference} can not convert to FileSystemAccessRule"); } } }
相关文章
- Linux学习之文件特殊权限详解(SetUID、SetGID、Sticky BIT)(十一)
- 怎么禁止共享盘删文件(单独的禁止删除权限):实现Win10中文件夹只允许写入不允许删除的功能
- Hadoop MapReduce处理海量小文件:自定义InputFormat和RecordReader
- vue-cli3文件的引入
- centos 文件权限问题chmod
- 鸟哥笔记-专题二:Linux文件和文件夹权限差异对比
- 将用户赋予sudo权限:配置sudoers文件
- EasyRTMP实现Demux解析MP4文件进行rtmp推送实现RTMP直播功能
- samba需求,请建一个目录,所有用户都可以修改其中的任意文件(新建文件的权限问题)
- 鸟哥笔记-专题一:Linux文件的权限rwx、特殊权限sst、隐藏权限ia
- C#修改文件或文件夹的权限,为指定用户、用户组添加完全控制权限
- Linux---文件特殊权限
- Android问题笔记 - Android10适配有权限但是无法读写sdcard中文件问题
- 已解决Python读取20GB超大文件内存溢出报错MemoryError
- 通过状态机方法实现基于FPGA的维特比译码器,包含testbench测试文件
- minio实现文件上传下载和删除功能
- [手游项目2]-4- lua判断文件是否存在
- Android 上实现非root的 Traceroute -- 非Root权限下移植可运行二进制文件 脚本文件
- ubuntu 16.04怎么更改文件夹里面所有子文件权限
- root 无法修改文件权限
- Linux文件权限管理
- 小技巧:一种简单的判断文件权限的方法
- Linux 的文件权限和目录配置
- windows下运行python文件路径总是出错?