为iis添加允许访问的ip(适用与7.0及以上版本)
为iis添加允许访问的ip(适用与7.0及以上版本)
--ip地址和域限制--添加一条默认允许条目--编辑功能设置--未指定的客户端访问权限:拒绝(除添加的ip之外其余ip均不能访问该网站)
下面程序为批量为多个网站添加一个可以访问网站的ip:
private static void AddAllowIP(string id)
{
try
{
// retrieve the directory entry for the root of the IIS server
System.DirectoryServices.DirectoryEntry IIS =
new System.DirectoryServices.DirectoryEntry(
"IIS://localhost/W3SVC/"+id+"/Root"); //id为网站标记ID
// retrieve the list of currently denied IPs
Console.WriteLine("Retrieving the list of currently denied IPs.");
// get the IPSecurity property
Type typ = IIS.Properties["IPSecurity"][0].GetType();
object IPSecurity = IIS.Properties["IPSecurity"][0];
// retrieve the IPDeny list from the IPSecurity object
Array origIPDenyList = (Array)typ.InvokeMember("IPGrant",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetProperty,
null, IPSecurity, null);
// display what was being denied
foreach (string s in origIPDenyList)
Console.WriteLine("Before: " + s);
Console.WriteLine("Updating the list of denied IPs.");
object[] newIPDenyList = new object[1];
newIPDenyList[0] = ConfigurationManager.AppSettings["newip"];
bool add=true;
foreach (string s in origIPDenyList)
{
string[] ip = s.Split(',');
if (ip[0].ToString() == newIPDenyList[0].ToString())
{
add=false;
}
}
if(add)
{
Console.WriteLine("Calling SetProperty");
// add the updated list back to the IPSecurity object
typ.InvokeMember("IPGrant",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty,
null, IPSecurity, new object[] { newIPDenyList });
IIS.Properties["IPSecurity"][0] = IPSecurity;
Console.WriteLine("Commiting the changes.");
// commit the changes
IIS.CommitChanges();
IIS.RefreshCache();
// check to see if the update took
Console.WriteLine("Checking to see if the update took.");
IPSecurity = IIS.Properties["IPSecurity"][0];
Array y = (Array)typ.InvokeMember("IPGrant",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetProperty,
null, IPSecurity, null);
foreach (string s in y)
Console.WriteLine("After: " + s);
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message.ToString());
}
}