使用ASP.NET来管理IIS

来源:互联网 发布:c语言 pointer 编辑:程序博客网 时间:2024/06/17 06:45

使用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);
}

%>