为IIS站点添加限制IP
Posted 简单就好。。。
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了为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;
}
以上是关于为IIS站点添加限制IP的主要内容,如果未能解决你的问题,请参考以下文章
Windows Server 2008 R2 IIS 服务的配置(缺陷)