平时经常需要维护具有很多远程桌面用户的系统里,可能会不小心运行了用户上传的EXE文件。
所以设计了这套程序,防止这种现象的事情发生。
using System; using System.IO; using System.Security.AccessControl; using System.DirectoryServices.AccountManagement; namespace xcacls { class Program { static void Main(string[] args) { denyExecuteFileOfAdminAtUsers(); Console.ReadKey(); } /// <summary> /// 禁止管理帐户对Users目录下所有文件的执行权限 /// </summary> static void denyExecuteFileOfAdminAtUsers() { Console.Title = "禁止管理帐户对Users目录下所有文件的执行权限"; string FileName = @"C:\Users\"; DirectoryInfo dInfo = new DirectoryInfo(FileName); foreach (DirectoryInfo dInfo2 in dInfo.GetDirectories()) { if (isExistUser(dInfo2.Name)) { bool ret = SetAccessControl_denyExecuteFile(dInfo2, @"BUILTIN\Administrators"); Console.WriteLine("dInfo2=>" + dInfo2.Name + " ret:" + ret.ToString()); } } Console.WriteLine("Finish."); } /// <summary> /// 禁止管理帐户对指定目录下所有文件的执行权限 /// </summary> /// <param name="dInfo"></param> /// <returns></returns> static bool SetAccessControl_denyExecuteFile(DirectoryInfo dInfo, string Account = @"BUILTIN\Administrators") { if (!dInfo.Exists) { return false; } //string Account = @"BUILTIN\Administrators"; FileSystemRights Rights = new FileSystemRights(); Rights = Rights | FileSystemRights.ExecuteFile; DirectorySecurity dSecurity = dInfo.GetAccessControl(); FileSystemAccessRule AccessRule2 = new FileSystemAccessRule(Account, Rights, InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Deny); bool modified; dSecurity.ModifyAccessRule(AccessControlModification.Add, AccessRule2, out modified); dInfo.SetAccessControl(dSecurity); return modified; } /// <summary> /// 判断用户名是否存在 /// </summary> /// <param name="username">用户名</param> /// <returns></returns> static bool isExistUser(string username) { PrincipalContext context = new PrincipalContext(ContextType.Machine); UserPrincipal userPrincipal1 = UserPrincipal.FindByIdentity(context, username); if (null == userPrincipal1) { return false; } return true; } /// <summary> /// 添加远程桌面用户 /// </summary> /// <param name="username">用户名</param> /// <param name="password">密码</param> /// <param name="displayName">显示名称</param> /// <returns>是否创建成功</returns> static bool addRemoteDesktopUser(string username, string password, string displayName = null) { PrincipalContext context = new PrincipalContext(ContextType.Machine); UserPrincipal user = new UserPrincipal(context); user.SetPassword(password); if (!string.IsNullOrEmpty(displayName)) { user.DisplayName = displayName; } user.Name = username; user.UserCannotChangePassword = true; user.PasswordNeverExpires = true; try { user.Save(); } catch (Exception ex) { return false; } GroupPrincipal group = GroupPrincipal.FindByIdentity(context, "Remote Desktop Users"); group.Members.Add(user); group.Save(); return true; } } }
飞儿传媒www.firadio.com