设为首页 收藏本站
查看: 3259|回复: 0

[经验分享] 使用ASP.NET来管理IIS

[复制链接]

尚未签到

发表于 2015-8-16 07:34:17 | 显示全部楼层 |阅读模式
使用ASP.NET来操作IIS,可以达到创建虚拟目录,虚拟站点,删除虚拟目录,列表等等功能.
关键:ASP.NET的用户权限不足以操作IIS,要授予一个高点的权限.
方法1,在web.config文件中加入这一行<identity impersonate="true" />,不过有风险.
方法2,使用假冒,我就是用这一方法,但还是有风险,
其它方法,略

  using System;
using System.IO;
using System.DirectoryServices;
  namespace com.todayisp.iismanager
{
/// <summary>
/// Summary description for IISManager.
/// </summary>
public class IISManager
{
  private DirectoryEntry _iisServer;
  //public int Counter = 10; //限制创建虚拟目录数量
  //创建一个虚拟目录
  public string CreateVDir(string WebSiteName,string nameDirectory,int Counter)
  {
  string SiteID = GetSiteID(WebSiteName);
   if (SiteID == null) return "error:该站点不存在.";
  _iisServer = new DirectoryEntry("IIS://localhost/W3SVC/" + SiteID);
   try
   {
    DirectoryEntry Web = _iisServer.Children.Find("Root","IIsWebVirtualDir");
    DirectoryEntry VD = Web.Children.Find(nameDirectory,"IIsWebVirtualDir");
    return "error:你要建立的虚拟目录已经存在.";
   }
   catch
   {
    try
    {
     DirectoryEntry folderRoot = _iisServer.Children.Find("Root","IIsWebVirtualDir");
  int Thecount=0;
     foreach(DirectoryEntry b1 in folderRoot.Children)
     {
      Thecount = Thecount + 1;
     }
  //如果虚拟目录数量没超过指定数量,则创建.
     if (Thecount < Counter)
     {
      string ThePath;
      ThePath=folderRoot.Properties["Path"].Value +"\\" + nameDirectory;
  //如果没有该目录,则创建一个真实目录
      DirectoryInfo di = Directory.CreateDirectory(ThePath);
  DirectoryEntry newVirDir = folderRoot.Children.Add(nameDirectory,"IIsWebVirtualDir");
      newVirDir.CommitChanges();
      // Set Properties
      newVirDir.Properties["AccessRead"].Add(true);
      newVirDir.Properties["Path"].Value = ThePath;
      //Create a Application;Don't use invoke method
      // Save Changes
      newVirDir.CommitChanges();
      folderRoot.CommitChanges();
      _iisServer.CommitChanges();
      newVirDir.Invoke("AppCreate",true);
      return "successful:你已经成功地创建了一个虚拟目录:" + nameDirectory;
     }
     else
     {
      return "error:你的站点的虚拟目录已经满" + Counter + "个,所以不能再创建.";
     }
    }
    catch(Exception e)
    {
     return "error:尝试进入该站点失败." + e.Message;
    }
   }
   
  }
  //删除虚拟目录
  public string DelVirtualDirectory(string WebSiteName,string nameDirectory)
  {
   try
   {
    string SiteID = GetSiteID(WebSiteName);
    if (SiteID == null) return "error:该站点不存在.";
  
    DirectoryEntry deRoot= new DirectoryEntry("IIS://localhost/W3SVC/" + SiteID + "/ROOT");
    try
    {
     DirectoryEntry deVDir = deRoot.Children.Find(nameDirectory, "IIsWebVirtualDir");
     deRoot.RefreshCache();
     deVDir = deRoot.Children.Find(nameDirectory, "IIsWebVirtualDir");
     deVDir.Invoke("AppDelete", null);
     deRoot.Children.Remove(deVDir);
     deRoot.CommitChanges();
     deRoot.Close();
     return "successful:删除虚拟目录" + nameDirectory + "成功!";
    }
    catch
    {
     return "error:该虚拟目录不存在.";
    }
   }
   catch(Exception e)
   {
    return "error:删除目录失败." + e.Message;
   }
  }
  //查找对应的虚拟站点.
  public string GetSiteID(string WebSiteName)
  {
   DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
   try
   {
    string SiteID= null;
    string hostname;
    foreach(DirectoryEntry bb in root.Children)
    {
     try
     {
      //if(Convert.ToInt32(bb.Name.Trim()) < 0) continue;
      PropertyValueCollection pvc = bb.Properties["ServerBindings"];
  String[] srvBindings = ((string)pvc[0]).Split(new char[] {':'});
      hostname = srvBindings[2].Trim();
  //判断,可换用hostname
      //if (WebSiteName == bb.Properties["ServerComment"].Value.ToString()) SiteID=bb.Name;
      if (WebSiteName == hostname) SiteID=bb.Name;
      // Clear Variable
      hostname = "";
     }
     catch{}
    }
    if (SiteID == null) return null;
    return SiteID;
   }
   catch
   {
    return null;
   }
  }
  //虚拟目录重命名
  public bool RenameVirtualDirectory(string WebSiteName,string nameDirectory,string NewName)
  {
   try
   {
    DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
   
    string SiteID="";
    string hostname;
    foreach(DirectoryEntry bb in root.Children)
    {
     try
     {
      //if(Convert.ToInt32(bb.Name.Trim()) < 0) continue;
      PropertyValueCollection pvc = bb.Properties["ServerBindings"];
      String[] srvBindings = ((string)pvc[0]).Split(new char[] {':'});
      hostname = srvBindings[2].Trim();
      if(hostname.Equals("")) hostname = "localhost";
  //判断,可换用hostname
      //if (WebSiteName == bb.Properties["ServerComment"].Value.ToString()) SiteID=bb.Name;
      if (WebSiteName == hostname) SiteID=bb.Name;
      // Clear Variable
      hostname = "";
     }
     catch{}
    }
   
    DirectoryEntry deRoot= new DirectoryEntry("IIS://localhost/W3SVC/" + SiteID + "/ROOT");
    DirectoryEntry deVDir = deRoot.Children.Find(nameDirectory, "IIsWebVirtualDir");
    deRoot.RefreshCache();
    deVDir = deRoot.Children.Find(nameDirectory, "IIsWebVirtualDir");
    deVDir.Rename("yeah");
    deRoot.CommitChanges();
    deRoot.Close();
    return true;
   }
   catch
   {
    return false;
   }
  }
  
  //创建虚拟站点的类,需要输入"站点名","站点根目录对应地址","端口".
  public bool CreateWebSite(string siteName,string Path,string Port)
  {
   try
   {
    DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
    // Find unused ID value for new web site
    int siteID = 1;
    foreach(DirectoryEntry ef in root.Children)
    {
     if(ef.SchemaClassName == "IIsWebServer")
     {
      int ID = Convert.ToInt32(ef.Name);
      if(ID >= siteID)
      {
       siteID = ID+1;
      }
     }
    }// Create web site
    DirectoryEntry site = (DirectoryEntry)root.Invoke("Create", "IIsWebServer", siteID);
    site.Invoke("Put", "ServerComment", siteName);
    site.Invoke("Put", "KeyType", "IIsWebServer");
    site.Invoke("Put", "ServerBindings", ":" + Port + ":");
    site.Invoke("Put", "ServerState", 2);
    site.Invoke("Put", "FrontPageWeb", 1);
    site.Invoke("Put", "DefaultDoc", "Default.aspx");
    site.Invoke("Put", "SecureBindings", ":443:");
    site.Invoke("Put", "ServerAutoStart", 1);
    site.Invoke("Put", "ServerSize", 1);
    site.Invoke("SetInfo");
    // Create application virtual
    DirectoryEntry siteVDir = site.Children.Add("Root", "IISWebVirtualDir");
    siteVDir.Properties["AppIsolated"][0] = 2;
    siteVDir.Properties["Path"][0] = Path;
    siteVDir.Properties["AccessFlags"][0] = 513;
    siteVDir.Properties["FrontPageWeb"][0] = 1;
    siteVDir.Properties["AppRoot"][0] = "/LM/W3SVC/"+siteID+"/Root";
    siteVDir.Properties["AppFriendlyName"][0] = "Root";
    siteVDir.CommitChanges();
    site.CommitChanges();
    return true;
   }
   catch
   {
   return false;
   }
  }
  
  //对虚拟站点的虚拟目录列表
  public string DirAll(string WebSiteName,string VDirName,string Path)
  {
   DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
   
   string SiteID="";
   string hostname;
   foreach(DirectoryEntry bb in root.Children)
   {
    try
    {
     //if(Convert.ToInt32(bb.Name.Trim()) < 0) continue;
     PropertyValueCollection pvc = bb.Properties["ServerBindings"];
     String[] srvBindings = ((string)pvc[0]).Split(new char[] {':'});
     hostname = srvBindings[2].Trim();
     if(hostname.Equals("")) hostname = "localhost";
  //判断,可换用hostname
     //if (WebSiteName == bb.Properties["ServerComment"].Value.ToString()) SiteID=bb.Name;
     if (WebSiteName == hostname) SiteID=bb.Name;
     // Clear Variable
     hostname = "";
    }
    catch{}
   }
  DirectoryEntry deRoot= new DirectoryEntry("IIS://localhost/W3SVC/" + SiteID + "/ROOT");
  if (VDirName == null)
   {
    string RealPath = deRoot.Properties["Path"].Value.ToString();
    string VPath = deRoot.Path;
    try
    {
     string AllDir = "";
     string cc = "<br>";
  foreach(DirectoryEntry a in deRoot.Children)
     {
      AllDir = AllDir + "<a href=?sitename=" + WebSiteName + "&vdir=" + a.Name + ">" + a.Name + "<br>";
     }
     DirectoryInfo di = new DirectoryInfo(RealPath);
     DirectoryInfo[] subdirectoryEntries = di.GetDirectories();
     foreach(DirectoryInfo subdirectory in subdirectoryEntries)
     {
      cc = cc + subdirectory.Name + "<br>";
     }
  
  return AllDir;
    }
    catch
    {
    }
    return "END";
   }
   else
   {
    DirectoryEntry subRoot = deRoot.Children.Find(VDirName,"IIsWebVirtualDir");
    string RealPath = subRoot.Properties["Path"].Value.ToString() + "\\" + Path + "\\";
    try
    {
     string cc = "<br>";
     string filename = "<br>";
  
     DirectoryInfo di = new DirectoryInfo(RealPath);
     DirectoryInfo[] subdirectoryEntries = di.GetDirectories();
     foreach(DirectoryInfo subdirectory in subdirectoryEntries)
     {
      cc = cc + "<a href='?sitename=" + WebSiteName + "&VDir=" + VDirName + "&Path=" + Path + @"\" + subdirectory.Name + "'>" + subdirectory.Name + "</a><br>";
     }
  // Create an array representing the files in the current directory.
     FileInfo[] fi = di.GetFiles();
     foreach (FileInfo fiTemp in fi)
     {
      filename = filename + fiTemp.Name + "<br>";
     }
  return cc + filename;
    }
    catch
    {
     return "NO" + Path;
    }
   
   }
  }
  
}
}
  使用方法如下: 在IISManager.aspx文件中
  <%@ Page language="c#" AutoEventWireup="false"%>
//<%@ Import Namespace= "com.todayisp.identity"%>
<%@ Import Namespace= "com.todayisp.iismanager"%>
<%
string WebSite = Request.Params["WebSite"];
string VDir = Request.Params["VDir"];
string ManageType = Request.Params["ManageType"];
int Counter = 2; //限制创建虚拟目录数量
//string UserName = Request.Params["UserName"];
//string Password = Request.Params["Password"];
  if (WebSite == null && VDir == null)
{
Response.Write("error:请输入站点名或目录名.");
return;
}
  //这部分为使用了RSA加密的解密方法
/*if (UserName == null && Password == null)
{
Response.Write("error:用户名和密码为空.");
return;
}
  try
{
IDEN Key = new IDEN();
string PasswordKey = Key.ChangeKey(Password);
if (PasswordKey == null) return;
}*/
  try
{ /*
  //假冒身份开始
  IDEN Identity = new IDEN();
  bool In = Identity.ChangeRoleIN(UserName,PasswordKey);
  if (!In){
   Response.Write("error:变更用户权限失败");
   return;
  }*/
  IISManager isMang = new IISManager();
  string test="";
  switch(ManageType)
  {
   case "Del":
    test = isMang.DelVirtualDirectory(WebSite,VDir);
    break;
   case "Create":
    test = isMang.CreateVDir(WebSite,VDir,Counter);
    break;
   default:
    Response.Write("error:没有选定操作类型.");
    break;
  }
  
  Response.Write(test);
  /*
  //假冒身份结束
  Identity.ChangeRoleOUT();
  */
}
catch(Exception e){
  Response.Write("error:" + e.Message);
}
  %>

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-99512-1-1.html 上篇帖子: IIS中配置REST服务svc文件支持的HTTP动作 下篇帖子: Windows7 IIS 7.5 错误
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表