/// <summary>
/// 添加站點(diǎn)限制IP
/// </summary>
/// <param name="sitename">站點(diǎn)名稱</param>
/// <param name="xzip">限制IP</param>
/// <param name="type">是否授權(quán)還是限制 0為授權(quán) 1為限制</param>
/// <param name="mask">子網(wǎng)掩碼 空 0 1 2</param>
/// <returns></returns>
public string AddAstrictIP(string sitename, string xzip, string cut,string mask)
{
string result = "";
//判斷子網(wǎng)掩碼是否為空
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
{
//根據(jù)站點(diǎn)名稱查詢站點(diǎn)對應(yīng)ID
string sitenum = getWebSiteNum(sitename); ;
//檢索為IIS服務(wù)器的根目錄條目
System.DirectoryServices.DirectoryEntry IIS = new System.DirectoryServices.DirectoryEntry(string.Format("IIS://localhost/w3svc/{0}/root", sitenum));//站點(diǎn)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)
{
// 必須設(shè)置 默認(rèn)允許訪問
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);
//獲取原來數(shù)據(jù)
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("當(dāng)文件已存在時(shí)"))
{
result = "針對此ip的限制已存在";
}
else
{
result = e.Message;
}
}
return result;
}
/// <summary>
/// 展示站點(diǎn)禁止ip列表
/// </summary>
/// <param name="sitename">站點(diǎn)名稱</param>
/// <returns></returns>
public string AstrictIPList(string sitename)
{
string str = "";
try
{
//根據(jù)站點(diǎn)名稱查詢站點(diǎn)對應(yīng)ID
string sitenum = getWebSiteNum(sitename); ;
string strr = string.Format("IIS://localhost/w3svc/{0}/root", sitenum);//站點(diǎn)ID號
//檢索為IIS服務(wù)器的根目錄條目
System.DirectoryServices.DirectoryEntry IIS = new System.DirectoryServices.DirectoryEntry(strr);
// 檢索當(dāng)前否認(rèn)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還是單個(gè)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('';'');//移除尾部匹配項(xiàng)
}
catch (Exception e)
{
}
return str;
}
/// <summary>
/// 展示站點(diǎn)授權(quán)ip列表
/// </summary>
/// <param name="sitename">站點(diǎn)名稱</param>
/// <returns></returns>
public string GrantIPList(string sitename)
{
string str = "";
try
{
//根據(jù)站點(diǎn)名稱查詢站點(diǎn)對應(yīng)ID
string sitenum = getWebSiteNum(sitename); ;
string strr = string.Format("IIS://localhost/w3svc/{0}/root", sitenum);//站點(diǎn)ID號
//檢索為IIS服務(wù)器的根目錄條目
System.DirectoryServices.DirectoryEntry IIS = new System.DirectoryServices.DirectoryEntry(strr);
// 檢索當(dāng)前否認(rèn)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還是單個(gè)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">站點(diǎn)名稱</param>
/// <param name="xzip">限制ip</param>
/// <returns></returns>
public string DelAstrictIP(string sitename, string xzip)
{
//判斷限制的IP中是否含有(),如果有則表示一組ip
if(xzip.Contains("("))
{
//替換字符串 清除空格 并移除最后一個(gè)字符串
xzip= xzip.Replace("(",",").Trim().TrimEnd('')'');
}
else
{
xzip += ",255.255.255.255";
}
string result = "";
//如果是IIS6
if (IISVersionMajor == "6")
{
try
{
//根據(jù)站點(diǎn)名稱查詢站點(diǎn)對應(yīng)ID
string sitenum = getWebSiteNum(sitename); ;
string strr = string.Format("IIS://localhost/w3svc/{0}/root", sitenum);//站點(diǎn)ID號
//檢索為IIS服務(wù)器的根目錄條目
System.DirectoryServices.DirectoryEntry IIS = new System.DirectoryServices.DirectoryEntry(strr);
// 檢索當(dāng)前否認(rèn)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操作,請?jiān)贗IS中手動(dòng)操作。";
}
catch (Exception ex)
{
return ex.Message;
}
}
return result;
}
/// <summary>
/// IIS7刪除限制IP
/// </summary>
/// <param name="sitename">站點(diǎn)名稱</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地址 子網(wǎng)掩碼 域名
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>
/// 刪除授權(quán)IP
/// </summary>
/// <param name="sitename">站點(diǎn)名稱</param>
/// <param name="sqip">授權(quán)ip</param>
/// <returns></returns>
public string DelGrantIP(string sitename, string sqip)
{
//判斷限制的IP中是否含有(),如果有則表示一組ip
if (sqip.Contains("("))
{
//替換字符串 清除空格 并移除最后一個(gè)字符串
sqip = sqip.Replace("(", ",").Trim().TrimEnd('')'');
}
else
{
sqip += ",255.255.255.255";
}
string result = "";
//邏輯代碼塊
if (IISVersionMajor == "6")
{
try
{
//根據(jù)站點(diǎn)名稱查詢站點(diǎn)對應(yīng)ID
string sitenum = getWebSiteNum(sitename); ;
string strr = string.Format("IIS://localhost/w3svc/{0}/root", sitenum);//站點(diǎn)ID號
//檢索為IIS服務(wù)器的根目錄條目
System.DirectoryServices.DirectoryEntry IIS = new System.DirectoryServices.DirectoryEntry(strr);
// 檢索當(dāng)前否認(rèn)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();
//更新數(shù)據(jù)
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操作,請?jiān)贗IS中手動(dòng)操作。";
}
catch (Exception ex)
{
return ex.Message;
}
}
return result;
}
該文章在 2019/9/4 23:37:45 編輯過