IIS站点权限设置

//创建管理用户

public string CreateUser(string sys_username, string sys_passwd)
{
     try
     {
        DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
        DirectoryEntry NewUser = AD.Children.Add(sys_username, "user");
        NewUser.Invoke("SetPassword", new object[] { sys_passwd });
        NewUser.Invoke("Put", new object[] { "Description", "网站'" + sys_username + "'的独立用户" });
        NewUser.Invoke("Put", "UserFlags", 66049);
        NewUser.CommitChanges();
        DirectoryEntry grp;
        if (IISVersionMajor == "6")
        {
            try
            {
               grp = AD.Children.Find("IIS_WPG", "group");
               if (grp != null)
               {
                   grp.Invoke("Add", new object[] { NewUser.Path.ToString() });
               }
            }
           catch (Exception ex)
           {
               string[] str = new string[] { "net user " + sys_username + " /del" };
               Cmd(str);
               if (ex.Message.Contains("调用目标发生了异常"))
               {
                      MessageBox.Show("您的系统初始化配置不完整,\n\n请【重启系统】后再进行操作" + "\n\n通常这种情况会在系统安装或重装后第一次打开时发生;\n\n重启后,系统会自动配置完善。", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
               }
              else
               {
                      MessageBox.Show(ex.Message + "__IIS" + IISVersionMajor);
               }
               return "error";
           }
       }
      else
      {
         try
         {
              grp = AD.Children.Find("IIS_IUSRS", "group");
              if (grp != null)
              {
                   grp.Invoke("Add", new object[] { NewUser.Path.ToString() });
              }
          }
          catch (Exception ex)
          {
               string[] str = new string[] { "net user " + sys_username + " /del" };
               Cmd(str);
               if (ex.Message.Contains("调用的目标发生了异常") || ex.Message.Contains("exception occurred"))
               {
                     MessageBox.Show("您的系统初始化配置不完整,\n\n请【重启系统】后再进行操作" + "\n\n通常这种情况会在系统安装或重装后第一次打开时发生;\n\n重启后,系统会自动配置完善。", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
               }
               else
              {
                     MessageBox.Show(ex.Message + "__IIS" + IISVersionMajor);
              }
              return "error";
          }
    }

           return null;
       }
       catch (Exception ex)
       {
           log("创建用户异常:"+ex.Message.ToString());
            return ex.Message;
        }
     }

//设置文件夹权限

     public void SetDirectoryQX(string sitename, string sitePath)
    {
         var security = new DirectorySecurity();
         string path = sitePath;
         try
         {

               // 设置文件夹独立用户权限
               security.AddAccessRule(new FileSystemAccessRule("Administrators", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
               security.AddAccessRule(new FileSystemAccessRule(sitename, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
               security.SetAccessRuleProtection(true, false);//取消继承父级文件夹权限
               Directory.SetAccessControl(path, security);
          }
          catch (Exception ex)
         {
                 MessageBox.Show("站点文件夹管理用户设置失败:" + ex.Message);
         }
    }

//设置站点匿名用户

     public void SetAnonymousUser(string sitename,string username,string userpwd)
     {
         //设置匿名用户
         try
         {
              using (Microsoft.Web.Administration.ServerManager serverManager = new Microsoft.Web.Administration.ServerManager())
              {
                     Microsoft.Web.Administration.Configuration config = serverManager.GetApplicationHostConfiguration();
                     Microsoft.Web.Administration.ConfigurationSection anonymousAuthenticationSection = config.GetSection("system.webServer/security/authentication/anonymousAuthentication", sitename);
                     anonymousAuthenticationSection["enabled"] = true;
                     anonymousAuthenticationSection["userName"] = username;
                     anonymousAuthenticationSection["password"] = userpwd;
                     serverManager.CommitChanges();
              }
         }
         catch (Exception ex) { log("添加站点匿名用户异常:" + ex.Message.ToString()); }
      }

//设置站点物理路径凭据

     public void ModifySitePJ(string sitename, string username, string userpwd)
     {
         DirectoryEntry rootEntry = GetSite(false, sitename);
         DirectoryEntry path = rootEntry.Children.Find("Root", "IISWebVirtualDir");
         try
         {
              path.Properties["UNCUserName"].Value = username; // Web服务器桥接文件服务器的UNC账户
              path.Properties["UNCPassword"].Value = userpwd;
              path.CommitChanges();
              path.Close();
           }
           catch (Exception ex) { log("设置站点物理路径凭据失败:" + ex.Message.ToString()); }
           finally { rootEntry.Dispose(); rootEntry.Close(); path.Dispose(); path.Close(); }
      }

     private DirectoryEntry GetSite(bool isRoot, string siteName)
     {
         DirectoryEntry itemEntry = null;
         try
         {
             //存放到缓存当中
             DirectoryEntry directoryEntity = new DirectoryEntry("IIS://localhost/W3SVC");
             directoryEntity.UsePropertyCache = true;
             directoryEntity.RefreshCache();
            if (isRoot)
            {
                return directoryEntity;
            }
            if (string.IsNullOrEmpty(siteName))
            {
                return null;
            }
            //取指定名称的站点
            foreach (DirectoryEntry item in directoryEntity.Children)
            {
                //获取站点
                if ("IIsWebServer".Equals(item.SchemaClassName))
                {
                      if (item.Properties["ServerComment"].Value != null && siteName.ToLower().Equals(item.Properties["ServerComment"].Value.ToString().ToLower()))
                      {
                            itemEntry = item;
                            break;
                       }
                 }
              }
          }
          catch (Exception ex) { }
          return itemEntry;
     }

//应用程序池标识独立用户

     public void ModappBS(string appPoolName, string username, string userpwd)
     {
         DirectoryEntry apppools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
         try
         {
                //找到站点物理路径

               foreach (DirectoryEntry entry in apppools.Children)
               {
                   if (entry.Name.Equals(appPoolName))
                   {
                         if (IISVersionMajor == "6")
                         {
                               //iis6
                               entry.Properties["AppPoolIdentityType"][0] = "3";
                               entry.Properties["WamUserName"][0] = username;
                               entry.Properties["WamUserPass"][0] = userpwd;
                          }
                          else
                          {
                               //IIS7+
                               entry.Properties["AppPoolIdentityType"].Value = Microsoft.Web.Administration.ProcessModelIdentityType.SpecificUser;
                               entry.Properties["WamUserName"].Value = username;
                               entry.Properties["WamUserPass"].Value = userpwd;
                          }
                 entry.CommitChanges();
                 entry.Close();
                }
            }
        }
        catch (Exception ex)
        {
              log("设置独立用户应用程序标识池异常:" + ex.Message.ToString());
         }
        finally { apppools.Dispose(); apppools.Close(); }
     }

 

转载于:https://www.cnblogs.com/gqrbkw/p/7359578.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值