为IIS站点添加限制IP

/// <summary>
/// 添加站点限制IP
/// </summary>
/// <param name="sitename">站点名称</param>
/// <param name="xzip">限制IP</param>
/// <param name="type">是否授权还是限制 0为授权 1为限制</param>
/// <param name="mask">子网掩码 空 0 1 2</param>
/// <returns></returns>
public string AddAstrictIP(string sitename, string xzip, string cut,string mask)
{
string result = "";
//判断子网掩码是否为空
if (mask=="0")
{
mask = "255.0.0.0";
}
else if (mask == "1")
{
mask = "255.255.0.0";
}
else if (mask == "2")
{
mask = "255.255.255.0";
}
else
{
mask = "255.255.255.255";
}
try
{
//根据站点名称查询站点对应ID
string sitenum = getWebSiteNum(sitename); ;
//检索为IIS服务器的根目录条目
System.DirectoryServices.DirectoryEntry IIS = new System.DirectoryServices.DirectoryEntry(string.Format("IIS://localhost/w3svc/{0}/root", sitenum));//站点ID号
Type typ = IIS.Properties["IPSecurity"][0].GetType();// 得到IPSecurity属性
object IPSecurity = IIS.Properties["IPSecurity"][0];
IIS.RefreshCache();
bool bGrantByDefault = (bool)typ.InvokeMember("GrantByDefault", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.Instance | BindingFlags.GetProperty, null, IPSecurity, null);
if (!bGrantByDefault)
{
// 必须设置 默认允许访问
typ.InvokeMember("GrantByDefault", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
| BindingFlags.SetProperty, null, IPSecurity, new object[] { true });
}
if (cut == "0")
{
//如果是IIS6
if (IISVersionMajor == "6")
{
// 检索IPGrant IPSecurity对象列表
Array origIPGrantList = (Array)typ.InvokeMember("IPGrant",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetProperty, null, IPSecurity, null);

//修改
List<string> iplist = new List<string>();
foreach (string s in origIPGrantList)
{
iplist.Add(s);
}
iplist.Add(string.Format("{0},{1}", xzip, mask));
bool bGrantByDefaultx = (bool)typ.InvokeMember("GrantByDefault",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetProperty,
null, IPSecurity, null);
if (bGrantByDefaultx)
{
typ.InvokeMember("GrantByDefault",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty,
null, IPSecurity, new object[] { false });
}

object[] newIPDenyList = new object[iplist.Count];
int i = 0;
foreach (string s in iplist)
{
newIPDenyList[i] = s;
i++;
}
typ.InvokeMember("IPGrant",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty,
null, IPSecurity, new object[] { newIPDenyList });

}
else
{
// 检索IPGrant IPSecurity对象列表
Array origIPGrantList = (Array)typ.InvokeMember("IPGrant",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetProperty, null, IPSecurity, null);
List<string> iplist = new List<string>();
foreach (string s in origIPGrantList)
{
iplist.Add(s);
}
//先删除后添加
foreach (string s in origIPGrantList)
{
if (iplist.Contains(s))
{ iplist.Remove(s); }
}
iplist.Add(string.Format("{0},{1}", xzip,mask));
bool bGrantByDefaultx = (bool)typ.InvokeMember("GrantByDefault",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetProperty,
null, IPSecurity, null);
if (bGrantByDefaultx)
{
typ.InvokeMember("GrantByDefault",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty,
null, IPSecurity, new object[] { false });
}

object[] newIPDenyList = new object[iplist.Count];
int i = 0;
foreach (string s in iplist)
{
newIPDenyList[i] = s;
i++;
}
typ.InvokeMember("IPGrant",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty,
null, IPSecurity, new object[] { newIPDenyList });
}
}
else
{
//如果是IIS6
if (IISVersionMajor == "6")
{
// 检索IPDeny IPSecurity对象列表
Array origIPDenyList = (Array)typ.InvokeMember("IPDeny",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetProperty, null, IPSecurity, null);
//获取原来数据
int num = origIPDenyList.Length;
object[] newIPDenyList = new object[num + 1];
int i = 0;
foreach (string s in origIPDenyList)
{
newIPDenyList[i] = s;
i++;
}
newIPDenyList[i] = string.Format("{0},{1}", xzip,mask);
typ.InvokeMember("IPDeny",//限制
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty, null, IPSecurity, new object[] { newIPDenyList });
}
else
{
//II7+
typ.InvokeMember("IPDeny",//限制
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty, null, IPSecurity, new object[] { string.Format("{0},{1}", xzip,mask) });
}
}
IIS.Properties["IPSecurity"][0] = IPSecurity;
// 提交更改
IIS.CommitChanges();
IIS.RefreshCache();
result = "succeed";
}
catch (Exception e)
{
string er = e.Message;
if (e.Message.Contains("当文件已存在时"))
{
result = "针对此ip的限制已存在";
}
else
{
result = e.Message;
}
}
return result;

}

/// <summary>
/// 展示站点禁止ip列表
/// </summary>
/// <param name="sitename">站点名称</param>
/// <returns></returns>
public string AstrictIPList(string sitename)
{
string str = "";
try
{
//根据站点名称查询站点对应ID
string sitenum = getWebSiteNum(sitename); ;
string strr = string.Format("IIS://localhost/w3svc/{0}/root", sitenum);//站点ID号
//检索为IIS服务器的根目录条目
System.DirectoryServices.DirectoryEntry IIS = new System.DirectoryServices.DirectoryEntry(strr);
// 检索当前否认IPs的列表
// 得到IPSecurity属性
Type typ = IIS.Properties["IPSecurity"][0].GetType();
object IPSecurity = IIS.Properties["IPSecurity"][0];
// 检索IPDeny IPSecurity对象列表
Array origIPDenyList = (Array)typ.InvokeMember("IPDeny",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetProperty, null, IPSecurity, null);
//显示被拒绝
foreach (string s in origIPDenyList)
{
//判断是一组ip还是单个ip
var m = s.Split(‘,‘);
if (m[1].Trim() != "255.255.255.255")
{
str += m[0] + "(" + m[1].Trim() + ")" + ";";
}
else
{
string ip = s.Substring(0, s.IndexOf(","));
str += ip + ";";
}
}
str = str.TrimEnd(‘;‘);//移除尾部匹配项
}
catch (Exception e)
{

}
return str;
}
/// <summary>
/// 展示站点授权ip列表
/// </summary>
/// <param name="sitename">站点名称</param>
/// <returns></returns>
public string GrantIPList(string sitename)
{
string str = "";
try
{
//根据站点名称查询站点对应ID
string sitenum = getWebSiteNum(sitename); ;
string strr = string.Format("IIS://localhost/w3svc/{0}/root", sitenum);//站点ID号
//检索为IIS服务器的根目录条目
System.DirectoryServices.DirectoryEntry IIS = new System.DirectoryServices.DirectoryEntry(strr);
// 检索当前否认IPs的列表
// 得到IPSecurity属性
Type typ = IIS.Properties["IPSecurity"][0].GetType();
object IPSecurity = IIS.Properties["IPSecurity"][0];
// 检索IPDeny IPSecurity对象列表
Array origIPDenyList = (Array)typ.InvokeMember("IPGrant",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetProperty, null, IPSecurity, null);
//显示被拒绝
foreach (string s in origIPDenyList)
{
//判断是一组ip还是单个ip
var m = s.Split(‘,‘);
if (m[1].Trim() != "255.255.255.255")
{
str += m[0] + "(" + m[1].Trim() + ")"+";";
}
else
{
string ip = s.Substring(0, s.IndexOf(","));
str += ip + ";";
}
}
str = str.TrimEnd(‘;‘);
}
catch (Exception e)
{

}
return str;
}
/// <summary>
/// 删除限制IP
/// </summary>
/// <param name="sitename">站点名称</param>
/// <param name="xzip">限制ip</param>
/// <returns></returns>
public string DelAstrictIP(string sitename, string xzip)
{
//判断限制的IP中是否含有(),如果有则表示一组ip
if(xzip.Contains("("))
{
//替换字符串 清除空格 并移除最后一个字符串
xzip= xzip.Replace("(",",").Trim().TrimEnd(‘)‘);
}
else
{
xzip += ",255.255.255.255";
}
string result = "";
//如果是IIS6
if (IISVersionMajor == "6")
{
try
{
//根据站点名称查询站点对应ID
string sitenum = getWebSiteNum(sitename); ;
string strr = string.Format("IIS://localhost/w3svc/{0}/root", sitenum);//站点ID号
//检索为IIS服务器的根目录条目
System.DirectoryServices.DirectoryEntry IIS = new System.DirectoryServices.DirectoryEntry(strr);
// 检索当前否认IPs的列表
// 得到IPSecurity属性
Type typ = IIS.Properties["IPSecurity"][0].GetType();
object IPSecurity = IIS.Properties["IPSecurity"][0];
// 检索IPDeny IPSecurity对象列表
Array origIPDenyList = (Array)typ.InvokeMember("IPDeny",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetProperty, null, IPSecurity, null);
//获取被拒绝的全部IP
List<object> newIpList = new List<object>();
foreach (string s in origIPDenyList)
{
//判断是否与选中的删除ip相等

if (s.Trim().Replace(" ", "")!= xzip.Trim())
{
newIpList.Add(s);
}

}
object[] ipList = newIpList.ToArray();
typ.InvokeMember("IPDeny",//限制
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty, null, IPSecurity, new object[] { ipList });
IIS.Properties["IPSecurity"][0] = IPSecurity;
// 提交更改
IIS.CommitChanges();
IIS.RefreshCache();
result = "succeed";
}
catch (Exception ex)
{
result = ex.Message;
}
}
else
{
//IIS7删除
try
{
string strr = DelIP(sitename, xzip);
result = strr; //"IIS7及以上版本暂不支持助手删除限制IP操作,请在IIS中手动操作。";
}
catch (Exception ex)
{
return ex.Message;
}

}
return result;
}
/// <summary>
/// IIS7删除限制IP
/// </summary>
/// <param name="sitename">站点名称</param>
/// <param name="xzip">IP地址</param>
/// <returns></returns>
public string DelIP(string sitename, string xzip)
{
//分隔字符串
var ipandmask = xzip.Split(‘,‘);
//==
try
{
using (Microsoft.Web.Administration.ServerManager serverManager = new Microsoft.Web.Administration.ServerManager())
{
Microsoft.Web.Administration.Configuration config = serverManager.GetApplicationHostConfiguration();
Microsoft.Web.Administration.ConfigurationSection ipSecuritySection = config.GetSection("system.webServer/security/ipSecurity", sitename);
Microsoft.Web.Administration.ConfigurationElementCollection ipSecurityCollection = ipSecuritySection.GetCollection();
Microsoft.Web.Administration.ConfigurationElement addElement = FindElementx(ipSecurityCollection, "add", "ipAddress", ipandmask[0].Trim(), "subnetMask", ipandmask[1].Trim(), "domainName", @"");//IP地址 子网掩码 域名
if (addElement == null) throw new InvalidOperationException("未找到元素!");
ipSecurityCollection.Remove(addElement);
serverManager.CommitChanges();
}
return "succeed";
}
catch (Exception ex)
{
return ex.Message;
}
}
private static Microsoft.Web.Administration.ConfigurationElement FindElementx(Microsoft.Web.Administration.ConfigurationElementCollection collection, string elementTagName, params string[] keyValues)
{
foreach (Microsoft.Web.Administration.ConfigurationElement element in collection)
{
if (String.Equals(element.ElementTagName, elementTagName, StringComparison.OrdinalIgnoreCase))
{
bool matches = true;
for (int i = 0; i < keyValues.Length; i += 2)
{
object o = element.GetAttributeValue(keyValues[i]);
string value = null;
if (o != null)
{
value = o.ToString();
}
if (!String.Equals(value, keyValues[i + 1], StringComparison.OrdinalIgnoreCase))
{
matches = false;
break;
}
}
if (matches)
{
return element;
}
}
}
return null;
}
/// <summary>
/// 删除授权IP
/// </summary>
/// <param name="sitename">站点名称</param>
/// <param name="sqip">授权ip</param>
/// <returns></returns>
public string DelGrantIP(string sitename, string sqip)
{
//判断限制的IP中是否含有(),如果有则表示一组ip
if (sqip.Contains("("))
{
//替换字符串 清除空格 并移除最后一个字符串
sqip = sqip.Replace("(", ",").Trim().TrimEnd(‘)‘);
}
else
{
sqip += ",255.255.255.255";
}
string result = "";
//逻辑代码块
if (IISVersionMajor == "6")
{
try
{
//根据站点名称查询站点对应ID
string sitenum = getWebSiteNum(sitename); ;
string strr = string.Format("IIS://localhost/w3svc/{0}/root", sitenum);//站点ID号
//检索为IIS服务器的根目录条目
System.DirectoryServices.DirectoryEntry IIS = new System.DirectoryServices.DirectoryEntry(strr);
// 检索当前否认IPs的列表
// 得到IPSecurity属性
Type typ = IIS.Properties["IPSecurity"][0].GetType();
object IPSecurity = IIS.Properties["IPSecurity"][0];
// 检索IPDeny IPSecurity对象列表
Array origIPDenyList = (Array)typ.InvokeMember("IPGrant",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetProperty, null, IPSecurity, null);
//获取被拒绝的全部IP
List<object> newIpList = new List<object>();
foreach (string s in origIPDenyList)
{
//判断是否与选中的删除ip相等

if (s.Trim().Replace(" ", "")!= sqip.Trim())

{
newIpList.Add(s);
}

}
object[] ipList = newIpList.ToArray();
//更新数据
typ.InvokeMember("IPGrant",//限制
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty, null, IPSecurity, new object[] { ipList });
IIS.Properties["IPSecurity"][0] = IPSecurity;
// 提交更改
IIS.CommitChanges();
IIS.RefreshCache();
result = "succeed";
}
catch (Exception ex)
{
result = ex.Message;
}
}
else
{

//IIS7删除
try
{
string strr = DelIP(sitename, sqip);
result = strr; //"IIS7及以上版本暂不支持助手删除限制IP操作,请在IIS中手动操作。";
}
catch (Exception ex)
{
return ex.Message;
}

}
return result;
}

时间: 2024-10-05 09:44:43

为IIS站点添加限制IP的相关文章

为IIS中的站点添加MIME映射

在IIS(Express)中默认不支持Json格式数据,数据总是无法加载,后来查了一下才知道是MIME映射的问题,所以需要在站点根目录下新建或者修改 Web.config 文件解决,添加或者修改 <system.webServer> 节点,方法如下: <?xml version="1.0"?> <configuration> <system.web> <compilation debug="false" targ

IIS站点/虚拟目录中访问共享目录(UNC)以及建立后的应用程序的信任级别问题

UNC是 Universal Naming Convention 的简称,也叫通用命名规范.通用命名约定.网络(范指局域网)上资源的完整位置名称.格式为 \\servername\sharename ,其中 servername 是服务器名,sharename 是共享资源的名称.目录或文件的 UNC 名称可以包括共享名称下的目录路径,如:\\servername\sharename\directory\filename亦可作为 \\serverip\sharename 格式,其中 serveri

利用ansible批量创建iis站点

准备: 系统必须大于等于windows2008 R2 系统 升级 PowerShell至3.0 安装iis 安装net ansible控制台目录结构 . ├── hosts #ansible 存放客户机IP ├── roles │   └── web │       ├── files │       │   └── web.ps1 # 创建iis站点ps脚本 │       └── tasks │           └── main.yml #ansible 控制脚本 └── web.yml

C#ASP.NET打包安装部署文件一键安装网站,包括IIS站点创建、数据库附加。

最近在开发web网站安装部署,以前从来没有做过web的安装打包没有头绪就开始上网查资料. 查了两天资料发现网上的资料要么不全要么就有错误,我就总结了网上的资料重新整理的一番,经过本人测试可用无错误 一下为借鉴部分资料的原文地址 此链接为打包ASP.NET网站资料(这个资料有问题,在自定义操作哪一步详情看下面文章):http://www.cnblogs.com/fish520/archive/2016/09/22/5882450.html 此链接为创建IIS站点(其中代码不全我还借鉴的部分其他论坛

IIS 站点部署多级域名

当站点的规模达到一定程度,往往会对业务进行拆分,部署到一台服务器的不同站点,,而一个域名(顶级域名)只能绑定一个站点(核心站点),这个时候就通过给顶级域名创建子域名的方式(理论上一个顶级域名可以绑定50个子域名),将子域名绑定到相关的业务站点.在通过修改host文件的方式,将所有的域名解析到当前的服务器IP,再通过IIS的主机头(子域名)解析到业务站点上,过程如下图: 现在IIS服务器上的站点如下: 主站点配置如下: 业务站点1配置如下: 业务站点2配置如下: 注意 (1).什么是子级域名: w

zabbix企业应用:利用自动发现监控IIS站点

如果一台windows server有许多个IIS站点,我们想实现这样一个监控目标:监控每个站点的状态.请求.流量.连接数,而且以后新增加的站点也可以自动加入到监控里,不需要再手动添加. 利用zabbix的自动发现(LLD)功能结合脚本可以实现上面的需求,实现对IIS站点的动态添加,动态监控. 先看一下监控的效果: 上图中的"Web Service(wskh)"是指IIS网站名称为wskh:"Web Service(_Total)"是指IIS下所有的站点. 网站流量

windows server 2008 R2服务器安装IIS并添加网站

一.安装IIS 1.在远程桌面上点开开始菜单栏,找到控制面板,并在控制面板下找到系统与安全 2.找到管理工具,在管理工具下点击服务器管理器 3.在服务器管理器下的角色中点击添加角色,点击下一步,进入角色选择 4.选择web服务器(IIS)项后,进入选择角色服务阶段 5.角色服务可以根据需要按照自己的需要进行选择(我这里是全选),点击下一步之后就可愉快地进行安装了. 经过一段漫长的等待,就会告诉我们安装成功了 三.添加或删除IIS角色服务 有时候我们在安装IIS时,我们选择的角色服务可能之后并不能

IIS站点报决绝访问Temporary ASP.NET Files的解决办法

IIS站点本来运行的好好的,突然就出现了:Temporary ASP.NET Files拒绝访问的问题.遇到此类问题,请逐步排查,定可解决. 原因:Windows操作系统升级导致. 办法: 1.检查C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files目录是否有IIS_IUSRS的读写权限和NETWORK SERVICE账户的读写权限,如果没有请添加. 2.检查c:\windows\目录下是否有目录Temp,如果

C#列表所有IIS站点以及相关站点属性

using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Windows.Forms.Design; using System.DirectoryServices; using System.Reflection; using System.Text.RegularExpressions; i