当前位置:   article > 正文

.net(c#)操作IIS大全_c# 获取iis指定网站访问ip

c# 获取iis指定网站访问ip

注意使用时要有服务器管理员权限 ,可在Web.config 添加

  1. <system.web>
  2. <identity impersonate="true" userName="服务器用户名" password="密码" />
  3. </system.web>


IISWorker

  1. using AppMain.model;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.DirectoryServices;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.NetworkInformation;
  8. using System.Text;
  9. using System.Text.RegularExpressions;
  10. using System.Threading.Tasks;
  11. namespace AppMain.bll
  12. {
  13. public class IISWorker
  14. {
  15. #region 获取IIS版本
  16. /// <summary>
  17. /// 获取本地IIS版本
  18. /// </summary>
  19. /// <returns></returns>
  20. public static string GetIIsVersion()
  21. {
  22. try
  23. {
  24. DirectoryEntry entry = new DirectoryEntry("IIS://localhost/W3SVC/INFO");
  25. string version = entry.Properties["MajorIISVersionNumber"].Value.ToString();
  26. return version;
  27. }
  28. catch (Exception se)
  29. {
  30. //说明一点:IIS5.0中没有(int)entry.Properties["MajorIISVersionNumber"].Value;属性,将抛出异常 证明版本为 5.0
  31. return string.Empty;
  32. }
  33. }
  34. #endregion
  35. #region 获取SiteID
  36. /// <summary>
  37. /// 获取最小SiteId,越小越好
  38. /// </summary>
  39. /// <returns></returns>
  40. public static int SiteId()
  41. {
  42. DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
  43. // Find unused ID value for new web site
  44. int siteID = 1;
  45. foreach (DirectoryEntry e in root.Children)
  46. {
  47. if (e.SchemaClassName == "IIsWebServer")
  48. {
  49. int ID = Convert.ToInt32(e.Name);
  50. if (ID >= siteID)
  51. {
  52. siteID = ID + 1;
  53. }
  54. }
  55. }
  56. return siteID;
  57. }
  58. #endregion
  59. #region 建IIS站点
  60. /// <summary>
  61. /// IIS站点
  62. /// </summary>
  63. /// <param name="webSiteName">站点名称</param>
  64. /// <param name="siteID">站点ID</param>
  65. /// <param name="port">站点端口</param>
  66. /// <param name="siteExplain">域名</param>
  67. /// <param name="defaultDoc">默认文档</param>
  68. /// <param name="pathToRoot">物理路径:d:\\iis\8001</param>
  69. /// <param name="UserId">应用程序池名称,如果没有自动创建</param>
  70. public static int CreateSite(string webSiteName,int siteID, string port, string siteExplain, string defaultDoc, string pathToRoot, string UserId)
  71. {
  72. int mark = 0;
  73. try
  74. {
  75. // createAppPool(siteExplain);
  76. DirectoryEntry de = new DirectoryEntry("IIS://localhost/" + "w3svc"); //从活动目录中获取IIS对象。
  77. object[] prams = new object[2] { "IIsWebServer", siteID };
  78. DirectoryEntry site = (DirectoryEntry)de.Invoke("Create", prams); //创建IISWebServer对象。
  79. site.Properties["KeyType"][0] = "IIsWebServer";
  80. site.Properties["ServerComment"][0] = webSiteName; //站点名称
  81. site.Properties["ServerState"][0] = 2; //站点初始状态,1.停止,2.启动,3
  82. site.Properties["ServerSize"][0] = 1;
  83. site.Properties["ServerBindings"].Add(":" + port + ":" + siteExplain); //站点端口
  84. site.CommitChanges(); //保存改变
  85. de.CommitChanges();
  86. DirectoryEntry root = site.Children.Add("Root", "IIsWebVirtualDir"); //添加虚拟目录对象
  87. root.Invoke("AppCreate", true); //创建IIS应用程序
  88. root.Invoke("AppCreate3", new object[] { 2, UserId, true }); //创建应用程序池,并指定应用程序池为"HostPool","true"表示如果HostPool不存在,则自动创建
  89. root.Properties["path"][0] = pathToRoot; //虚拟目录指向的物理目录
  90. root.Properties["EnableDirBrowsing"][0] = true;//目录浏览
  91. root.Properties["AuthAnonymous"][0] = true;
  92. root.Properties["AccessExecute"][0] = true; //可执行权限
  93. root.Properties["AccessRead"][0] = true;
  94. root.Properties["AccessWrite"][0] = true;
  95. root.Properties["AccessScript"][0] = true;//纯脚本
  96. root.Properties["AccessSource"][0] = false;
  97. root.Properties["FrontPageWeb"][0] = false;
  98. root.Properties["KeyType"][0] = "IIsWebVirtualDir";
  99. root.Properties["AppFriendlyName"][0] = siteExplain; //应用程序名
  100. root.Properties["AppIsolated"][0] = 2;
  101. root.Properties["DefaultDoc"][0] = defaultDoc; //默认文档
  102. root.Properties["EnableDefaultDoc"][0] = true; //是否启用默认文档
  103. root.CommitChanges();
  104. site.CommitChanges();
  105. root.Close();
  106. site.Close();
  107. de.CommitChanges(); //保存
  108. site.Invoke("Start", null); //除了在创建过程中置初始状态外,也可在此调用方法改变状态
  109. mark = 1;
  110. }
  111. catch(Exception ex)
  112. {
  113. mark = 0;
  114. }
  115. return mark;
  116. }
  117. #endregion
  118. #region 删除站点
  119. public static void DelSite(string siteName)
  120. {
  121. string siteNum = GetWebSiteNum(siteName);
  122. string siteEntPath = String.Format("IIS://{0}/w3svc/{1}", "localhost", siteNum);
  123. DirectoryEntry siteEntry = new DirectoryEntry(siteEntPath);
  124. string rootPath = String.Format("IIS://{0}/w3svc", "localhost");
  125. DirectoryEntry rootEntry = new DirectoryEntry(rootPath);
  126. rootEntry.Children.Remove(siteEntry);
  127. rootEntry.CommitChanges();
  128. }
  129. #endregion
  130. #region 域名绑定方法
  131. public static int AddHostHeader(int siteid, string ip, int port, string domain)//增加主机头(站点编号.ip.端口.域名)
  132. {
  133. int mark = 0;
  134. try
  135. {
  136. DirectoryEntry site = new DirectoryEntry("IIS://localhost/W3SVC/" + siteid);
  137. PropertyValueCollection serverBindings = site.Properties["ServerBindings"];
  138. string headerStr = string.Format("{0}:{1}:{2}", ip, port, domain);
  139. if (!serverBindings.Contains(headerStr))
  140. {
  141. serverBindings.Add(headerStr);
  142. }
  143. site.CommitChanges();
  144. mark = 1;
  145. }
  146. catch
  147. {
  148. mark = 0;
  149. }
  150. return mark;
  151. }
  152. #endregion
  153. #region 删除主机头
  154. public static void DeleteHostHeader(int siteid, string ip, int port, string domain)//删除主机头(站点编号.ip.端口.域名)
  155. {
  156. DirectoryEntry site = new DirectoryEntry("IIS://localhost/W3SVC/" + siteid);
  157. PropertyValueCollection serverBindings = site.Properties["ServerBindings"];
  158. string headerStr = string.Format("{0}:{1}:{2}", ip, port, domain);
  159. if (serverBindings.Contains(headerStr))
  160. {
  161. serverBindings.Remove(headerStr);
  162. }
  163. site.CommitChanges();
  164. }
  165. #endregion
  166. #region 创建应用程序池
  167. static void createAppPool(string AppPoolName)
  168. {
  169. DirectoryEntry newpool;
  170. DirectoryEntry apppools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
  171. newpool = apppools.Children.Add(AppPoolName, "IIsApplicationPool");
  172. newpool.CommitChanges();
  173. }
  174. #endregion
  175. #region 删除应用程序池
  176. public void deleteAppPool(string AppPoolName)
  177. {
  178. bool ExistAppPoolFlag = false;
  179. try
  180. {
  181. DirectoryEntry apppools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
  182. foreach (DirectoryEntry a in apppools.Children)
  183. {
  184. if (a.Name == AppPoolName)
  185. {
  186. ExistAppPoolFlag = true;
  187. a.DeleteTree();
  188. // MessageBox.Show("应用程序池名称删除成功", "删除成功");
  189. }
  190. }
  191. if (ExistAppPoolFlag == false)
  192. {
  193. // MessageBox.Show("应用程序池未找到", "删除失败");
  194. }
  195. }
  196. catch
  197. {
  198. //MessageBox.Show(ex.Message, "错误");
  199. }
  200. }
  201. #endregion
  202. #region 获取指定网站siteID
  203. /// <summary>
  204. /// 获取指定网站siteID
  205. /// </summary>
  206. /// <param name="siteName">站点名称</param>
  207. /// <returns></returns>
  208. public static string GetWebSiteNum(string siteName)
  209. {
  210. Regex regex = new Regex(siteName);
  211. string tmpStr;
  212. string entPath = String.Format("IIS://{0}/w3svc", "localhost");
  213. DirectoryEntry ent = new DirectoryEntry(entPath);
  214. foreach (DirectoryEntry child in ent.Children)
  215. {
  216. if (child.SchemaClassName == "IIsWebServer")
  217. {
  218. if (child.Properties["ServerBindings"].Value != null)
  219. {
  220. tmpStr = child.Properties["ServerBindings"].Value.ToString();
  221. if (regex.Match(tmpStr).Success)
  222. {
  223. return child.Name;
  224. }
  225. }
  226. if (child.Properties["ServerComment"].Value != null)
  227. {
  228. tmpStr = child.Properties["ServerComment"].Value.ToString();
  229. if (regex.Match(tmpStr).Success)
  230. {
  231. return child.Name;
  232. }
  233. }
  234. }
  235. }
  236. return "没有找到要删除的站点";
  237. }
  238. #endregion
  239. #region 获取IIS站点列表
  240. /// <summary>
  241. /// 获取站点列表
  242. /// </summary>
  243. public static List<IISInfo> GetServerBindings()
  244. {
  245. List<IISInfo> iisList = new List<IISInfo>();
  246. string entPath = "IIS://localhost/w3svc";
  247. DirectoryEntry ent = new DirectoryEntry(entPath);
  248. foreach (DirectoryEntry child in ent.Children)
  249. {
  250. if (child.SchemaClassName.Equals("IIsWebServer", StringComparison.OrdinalIgnoreCase))
  251. {
  252. if (child.Properties["ServerBindings"].Value != null)
  253. {
  254. object objectArr = child.Properties["ServerBindings"].Value;
  255. string serverBindingStr = string.Empty;
  256. if (objectArr is Array)//如果有多个绑定站点时
  257. {
  258. object[] objectToArr = (object[])objectArr;
  259. serverBindingStr = objectToArr[0].ToString();
  260. }
  261. else//只有一个绑定站点
  262. {
  263. serverBindingStr = child.Properties["ServerBindings"].Value.ToString();
  264. }
  265. IISInfo iisInfo = new IISInfo();
  266. iisInfo.DomainPort = serverBindingStr;
  267. iisInfo.AppPool = child.Properties["AppPoolId"].Value.ToString();//应用程序池
  268. iisInfo.ServerComment = child.Properties["ServerComment"].Value.ToString();
  269. iisInfo.physicalPath = GetWebsitePhysicalPath(child);
  270. iisList.Add(iisInfo);
  271. }
  272. }
  273. }
  274. return iisList;
  275. }
  276. #endregion
  277. #region 获取网站的物理路径
  278. /// <summary>
  279. /// 得到网站的物理路径
  280. /// </summary>
  281. /// <param name="rootEntry">网站节点</param>
  282. /// <returns></returns>
  283. public static string GetWebsitePhysicalPath(DirectoryEntry rootEntry)
  284. {
  285. string physicalPath = "";
  286. foreach (DirectoryEntry childEntry in rootEntry.Children)
  287. {
  288. if ((childEntry.SchemaClassName == "IIsWebVirtualDir") && (childEntry.Name.ToLower() == "root"))
  289. {
  290. if (childEntry.Properties["Path"].Value != null)
  291. {
  292. physicalPath = childEntry.Properties["Path"].Value.ToString();
  293. }
  294. else
  295. {
  296. physicalPath = "";
  297. }
  298. }
  299. }
  300. return physicalPath;
  301. }
  302. #endregion
  303. #region 判断端口是否被占用
  304. /// <summary>
  305. /// 判断端口是否被占用
  306. /// </summary>
  307. /// <param name="port">端口号</param>
  308. /// <returns></returns>
  309. public static bool PortInUse(int port)
  310. {
  311. bool inUse = false;
  312. IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
  313. IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();
  314. foreach (IPEndPoint endPoint in ipEndPoints)
  315. {
  316. if (endPoint.Port == port)
  317. {
  318. inUse = true;
  319. break;
  320. }
  321. }
  322. return inUse;
  323. }
  324. #endregion
  325. }
  326. }

IISInfo类

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace AppMain.model
  7. {
  8. public class IISInfo
  9. {
  10. /// <summary>
  11. /// 站点+端口
  12. /// </summary>
  13. public string DomainPort { get; set; }
  14. /// <summary>
  15. /// 应用程序池
  16. /// </summary>
  17. public string AppPool { get; set; }
  18. /// <summary>
  19. /// 网站名称
  20. /// </summary>
  21. public string ServerComment { get; set; }
  22. /// <summary>
  23. /// 物理路径
  24. /// </summary>
  25. public string physicalPath { get; set; }
  26. }
  27. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/252226
推荐阅读
相关标签
  

闽ICP备14008679号