博瑞博客

青春是一个充满活力的季节,即便是我们失去了天使的翅膀,只要我们还有一颗青春的心,那么我们的生活依然能够如阳光般灿烂!......
现在位置:首页 > 服务器 > Windows > iis7 7.5 用VB新建网站

iis7 7.5 用VB新建网站

江湖    Windows    2016-2-10    1667    0评论

Set oService = GetObject("winmgmts:root\WebAdministration")



'Create Binding for site



Set oBinding = oService.Get("BindingElement").Spawnlnstance

oBinding.BingingInformation = "*:80:www.site.com"

oBinging.Protocol = "http"



'Create site

oService.Get("Site").Create


  "NewSite",array(oBinging), "C:\inetpub\wwwroot"

  

'Create application  

oService.Get("Application").Create

  "/foo", "NewSite",array(oBinging), "C:\inetpub\wwwroot"





####################################################################







' Connect to the WMI WebAdministration namespace.'

Set oWebAdmin = GetObject("winmgmts:root\WebAdministration")



' Retrieve the application and display its Web site name and path.'

Set oApp = oWebAdmin.Get("Application.SiteName='Default Web Site',Path='/site'")



' Specify a new application pool name and save it.'

oApp.ApplicationPool = "NewAppPool"

oApp.Put








Set oWebAdmin = GetObject("winmgmts:root\WebAdministration")

Set oSite = oWebAdmin.Get("Site.Name='Site'")

oSite.ApplicationDefaults.ApplicationPool = "NewAppPool"

oSite.Put





####################################################################

以下方法自微软

####################################################################





使用 Windows Management Instrumentation (WMI)

您可以使用 Windows? Management Instrumentation (WMI) 在指令碼或編譯的程式中設定 IIS。所做的變更會立即生效,無需停止伺服器後再重新啟動。

優點

使用 WMI 設定大型網站或多個伺服器速度較快,而且 efficient.WMI 也具備指令碼設計功能。以下是 WMI 指令碼範例。

缺點

如果您建立站台或虛擬目錄,或者使用相依於其他內容的內容,您也必須確定哪些是應該建立和設定的支援內容。

以下程式碼可以用來建立網站和應用程式集區。

If WScript.Arguments.Count < 4 Then 

    WScript.Echo "Not enough parameters. Enter: username | web site name | app pool password | site ID" 

    WScript.Quit

End If



userName = WScript.Arguments(0) 

siteName = WScript.Arguments(1)

appPoolPassword = WScript.Arguments(2)

siteID = WScript.Arguments(3) 

appPoolName = "apppool
" & siteName

physicalPath = "\server\share" & userName & "\" & siteName [slg1] [slg2] 



Set oIIS = GetObject("winmgmts:root\WebAdministration")



Set oBinding = oIIS.Get("BindingElement").SpawnInstance

oBinding.BindingInformation = "*:80:" & siteName

oBinding.Protocol = "http"



Set oBinding2 = oIIS.Get("BindingElement").SpawnInstance


oBinding2.BindingInformation = ":80:www." & siteName

oBinding2.Protocol = "http"

arrBindings = array(oBinding, oBinding2)



Set oSiteDefn = oIIS.Get("Site")

oSiteDefn.Create siteName, arrBindings, physicalPath

WScript.Echo "Site created"



WScript.Sleep(100)



Set oSite = oIIS.Get("Site.Name='" & siteName & "'")

oSite.ID = siteID 

oSite.Put



Set oSite = oIIS.Get("Site.Name='" & siteName & "'")

appPoolUserName = "poolname
" & siteID



Set oAppDefn = oIIS.Get("ApplicationPool")

oAppDefn.Create appPoolName

WScript.Echo "App pool created"



WScript.Sleep(3000)



Set oAppDefn = oIIS.Get("ApplicationPool.Name='" & appPoolName & "'")

oAppDefn.ProcessModel.IdentityType = 3

oAppDefn.ProcessModel.Username = appPoolUserName

oAppDefn.ProcessModel.Password = appPoolPassword

oAppDefn.Put 



WScript.Echo "Identity set for App Pool"



Set oSiteDefn = oIIS.Get("Site.Name='" & siteName & "'")

oSiteDefn.ApplicationDefaults.ApplicationPool = appPoolName

oSiteDefn.Put


WScript.Echo "Site assigned to pool"



Set oSite = oIIS.Get("Site.Name='" & siteName & "'")

oSite.Start







####################################################################

以下方法自微软

####################################################################





使用 AppCmd.exe

AppCmd.exe 可以用於佈建網站以及執行很多命令來編輯設定。

以下的程式碼範例可以用來建立站台和應用程式集區 (包含失敗要求的追蹤和 W3svc 記錄檔位置)。

%windir%\system32\inetsrv\Appcmd add AppPool -name:%poolname% -processModel.username:%poolaccount% -processModel.password:%poolaccountpwd% -enable32BitAppOnWin64:true



%windir%\system32\inetsrv\AppCmd add site -name:%sitename% -bindings:http/
:80:%sitename% -physicalPath:%sitepath% -logfile.directory:%W3svclogpath% -traceFailedRequestsLogging.directory:%FREBlogpath%



%windir%\system32\inetsrv\Appcmd set app -app.name:%sitename%/ -applicationPool:%poolname%

您可以使用以下的程式碼來設定「失敗要求的追蹤」記錄檔位置:

%windir%\system32\inetsrv\AppCmd set config <sitename> -section:traceFailedRequestsLogging.directory:\remoteserver\content$\<sitename>\logs\failedReqLog

您可以使用以下程式碼來設定 W3SVC 記錄檔位置:

%windir%\system32\inetsrv\AppCmd set config <sitename> -section:-logfile.directory:\remotefileshare\content$\<sitename>\logs\logfiles







####################################################################

以下方法自微软

####################################################################





使用 Managed API (Microsoft.Web.Administration)

您可以使用 Microsoft.Web.Administration 的 Managed 應用程式設計介面 (API),在任何 Microsoft? .NET 應用程式設定 IIS。Microsoft.Web.Administration 是 IIS 7 的新 API,可以讓開發人員使用 Managed 程式碼輕鬆讀取以及操控伺服器設定。

優點

利用 Microsoft.Web.Administration,可以快速、有效設定大型網站或多部伺服器。針對遠端伺服器設定進行遠端程序呼叫 (RPC),就可以管理 Microsoft.Web.Administration。

Microsoft.Web.Administration 最快可以在 62 秒內建立多達 100,000 個站台 (大約每秒建立 1,600 個網站)。

缺點

Microsoft.Web.Administration 只能用於 Windows? 作業系統。很多物件並不是以「強型別」的形式公開,因此您必須瞭解較底層的 API,才能設定特定的物件和內容。

以下程式碼可以用來建立站台和應用程式集區,以及設定暫時的編譯目錄。

using System;

using System.Collections.Generic;

using System.Text;

using System.Diagnostics;

using Microsoft.Web.Administration;





namespace IIS7Demos

{

   class CreateSites

   {

      const int NUMBEROFSITES = 100;

      const int SITEBASENUMBER = 1000;

      const string POOLPREFIX = "POOL_";

      const string SITENAMEPREFIX = "SITE";

      const string ROOTDIR = "e:\content"; 



   static void Main(string[] args)

   { 

      ServerManager mgr = new ServerManager();

      SiteCollection sites = mgr.Sites;



      Stopwatch watch = new Stopwatch();

      watch.Start();



      for (int i = SITEBASENUMBER; i < NUMBEROFSITES+SITEBASENUMBER; i++)

      {

         if (!CreateSitesInIIS(sites, SITENAMEPREFIX, i, ROOTDIR))

         {

            Console.WriteLine("Creating site {0} failed", i);

         }



         if (!CreateAppPoolInIIS(mgr, SITENAMEPREFIX, i))

         {

            Console.WriteLine("Creating apppool {0} failed", i);

         }

      }



      mgr.CommitChanges();

      watch.Stop();

      Console.WriteLine("Creating {0} sites took {1} seconds", NUMBEROFSITES, ((double)watch.ElapsedMilliseconds) / 1000f);

   }



   static bool CreateSitesInIIS(SiteCollection sites, string sitePrefix, int siteId, string dirRoot)

   {

      string siteName = sitePrefix + siteId;

      // site gets set to Poolname using the following format. Example: 'Site_POOL10'

      string poolName = POOLPREFIX + sitePrefix + siteId;



      try

      {

         Site site = sites.CreateElement();

         site.Id = siteId;

         site.SetAttributeValue("name", siteName);

         sites.Add(site);



         Application app = site.Applications.CreateElement();

         app.SetAttributeValue("path", "/");

         app.SetAttributeValue("applicationPool", poolName);

         site.Applications.Add(app);



         VirtualDirectory vdir = app.VirtualDirectories.CreateElement();

         vdir.SetAttributeValue("path", "/");

         vdir.SetAttributeValue("physicalPath", dirRoot + @"\" + siteName);



         app.VirtualDirectories.Add(vdir);



         Binding b = site.Bindings.CreateElement();

         b.SetAttributeValue("protocol", "http");

         b.SetAttributeValue("bindingInformation", ":80:" + siteName);

         site.Bindings.Add(b);

      }

      catch (Exception ex)

      {

         Console.WriteLine("Create site {0} failed. Reason: {1}", siteName, ex.Message);

         return false;

      }

      return true;

   }



   static bool CreateAppPoolInIIS(ServerManager mgr, string sitePrefix, int siteId)

   {

      string poolName = POOLPREFIX + sitePrefix + siteId;



      try

      {

         mgr.ApplicationPools.Add(poolName);

         ApplicationPool apppool = mgr.ApplicationPools[poolName];

         apppool.ManagedPipelineMode = ManagedPipelineMode.Integrated;

      }



      catch (Exception ex)

      {

         Console.WriteLine("Create site {0} failed. Reason: {1}", poolName, ex.Message);

         return false;

      }

      return true;

   }

  }

}

若要為每個站台設定唯一的暫時編譯目錄,請使用以下程式碼:

using System;

using Microsoft.Web.Administration;

public class setASPNETCompilationDirectory

{

   static void Main()

   {

      ServerManager manager = new ServerManager();

      Configuration rootConfig = manager.GetWebConfiguration(new WebConfigurationMap(), null);

      ConfigurationSection section = rootConfig.GetSection("system.web/compilation");

      section.Attributes["tempDirectory"].Value = @"e:\inetpub\temp\temporary asp.net files\site1";

      section.SetMetadata("lockAttributes", "tempDirectory");

      manager.CommitChanges();

   }

}



####################################################################



####################################################################





指定匿名访问用户,IIS6比较简单,

在IIsWebVirtualDirSetting有两个属性

可以设置到:AnonymousUserName、AnonymousUserPass,

代码如下



ConnectionOptions co = new ConnectionOptions();

co.Authentication = AuthenticationLevel.PacketPrivacy;

ManagementPath iisPath = new ManagementPath();

iisPath.NamespacePath = @"root/MicrosoftIISv2";

ManagementScope scope = new ManagementScope(iisPath, co);

scope.Connect();



string website="esintest6" ;//站点名

int siteId=1;//站点Id,IIS6很多操作都需要得到该ID才能继续

//获取website

ObjectQuery query = new ObjectQuery(

string.Format(@"SELECT Name FROM IIsWebServerSetting where ServerComment='{0}' ", website));

ManagementObjectSearcher searcher =new ManagementObjectSearcher(scope, query);



ManagementObjectCollection queryCollection = searcher.Get();

foreach (ManagementObject mo in queryCollection)

{

    siteId = mo.Properties["Name"].Value.ToString().Replace("W3SVC/", "");

     break;

 }//开始设置

ManagementObject siteObj=new ManagementObject(Scope,new ManagementPath(string.Format(

                              @"{0}.Name='{1}'", "IIsWebServerSetting ",  string.Format("W3SVC/{0}/root", siteId))), null);

siteObj.Properties["AnonymousUserName"].Value = "iusr_esintest6";//这里是系统用户

siteObj.Properties["AnonymousUserPass"].Value = "1qaz@wsx#edc";//对应的密码

siteObj.Put();





IIS7相对复杂一点,是通过AnonymousAuthenticationSection BasicAuthenticationSection类型

来设定的(研究了大半天才发现这个用法,

太感谢这个http://forums.iis.net/t/1150268.aspx了)。



ConnectionOptions co = new ConnectionOptions();

co.Authentication = AuthenticationLevel.PacketPrivacy;

ManagementPath iisPath = new ManagementPath();

iisPath.NamespacePath = @"root/webadministration";

ManagementScope scope = new ManagementScope(iisPath, co);

scope.Connect();



string website="esintest6" ;//站点名



//开始设置

ManagementObject website = new ManagementObject(scope, new ManagementPath(string.Format("Site.name='{0}'",website)), null);

ManagementBaseObject inParams = website.GetMethodParameters("GetSection");

inParams["SectionName"] = "AnonymousAuthenticationSection";

ManagementBaseObject oo = website.InvokeMethod("GetSection", inParams, null) as ManagementBaseObject;

ManagementBaseObject returnedSection = oo["Section"] as ManagementBaseObject;

ManagementObject retval = new ManagementObject(scope, new ManagementPath("AnonymousAuthenticationSection.Path='" +

       returnedSection["Path"].ToString().Replace("/"+website, "") + "',Location='"+website+"'"), null);

retval.Get();



retval.Properties["Enabled"].Value = true;

retval.Properties["Location"].Value = website;

retval.Properties["UserName"].Value = "iusr_esintest6";//这里是系统用户

retval.Properties["Password"].Value = "1qaz@wsx#edc";//对应的密码



retval.Put();







###################################################################3

00000000000500.000000:000

###################################################################3




























评论一下分享本文赞助博瑞

赞助博瑞X

扫码赞助博瑞
联系站长
博瑞博客
挤眼亲亲咆哮开心想想可怜糗大了委屈哈哈小声点右哼哼左哼哼疑问坏笑赚钱啦悲伤耍酷勾引厉害握手耶嘻嘻害羞鼓掌馋嘴抓狂抱抱围观威武给力
提交评论

清空信息
关闭评论