我需要拒绝在Windows防火墙中访问大约50,000个IP地址; netsh advfirewall
只允许我添加约700.这是如何实现的?
看起来像你可以使用AC#应用程序以编程方式将规则添加到Windows防火墙。 您需要添加对位于c:\windows\system32
FirewallAPI.dll
的引用
做这样的事情:
using NetFwTypeLib; // Located in FirewallAPI.dll ... INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance( Type.GetTypeFromProgID("HNetCfg.FWRule")); firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK; firewallRule.Description = "Block this!"; firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; firewallRule.Enabled = true; firewallRule.InterfaceTypes = "All"; firewallRule.RemoteAddresses = "xxxx" //or xxxx,xxxx,... See Note 1 firewallRule.Name = "Block IP xxxx"; INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance( Type.GetTypeFromProgID("HNetCfg.FwPolicy2")); firewallPolicy.Rules.Add(firewallRule);
注1:您可以尝试制作5万个独立的规则(此代码添加1个规则),或将5万个远程IP添加到1个规则。
这是为了入站阻塞,如果你想出站阻塞以及改变方向。
参考:从任何方式改变使用C#在Windows中的“互联网”? 和https://msdn.microsoft.com/en-us/library/aa366458(VS.85).aspx
不幸的是,由于控制台的限制, netsh advfirewall
命令每行只能执行大约8192个字符(每个规则约550-1k个IP)。
要使用此方法添加无限数量的IP块,必须将逗号分隔的IP列表分割成不超过8k个字符的块,或将它们添加为单个IP块(这可能是不受欢迎的,因为它将泛洪列表你的防火墙规则!)
我已经在TCL中这样做了,但是如果有人知道如何将txt文件分割成不超过8k个字符的DOS变量块,或者将IP添加到不超过8k个字符的变量 – 在这里也可以:)
这里是TCL编码…在文件中找到逗号分隔的IP列表: comma_seperated_iplist.txt
set readfile [open "comma_seperated_iplist.txt" r]; # Open the comma seperated IP list file set ip_list [read $out]; # read the whole file into 1 variable close $readfile; # close the file, no longer needed catch {exec netsh advfirewall firewall delete rule name=IPBlocks}; # remove any old entries if {[string length $ip_list] < 8000} { # if under 8000 characters, just add them directly to 1 firewall entry catch {exec netsh advfirewall firewall add rule name="IPBlocks" protocol=any dir=in action=block remoteip=$ip_list} } else { # if over 8000 characters, break up into 8000 components and add each firewall rule set startpos 0; # set the search starting position (begining) set add_ip_range "1"; # set the start range IP list to anything while {$add_ip_range !=""} {; # loop until the start range IP list is empty # set the IP range contents to check up to set compare_ip_range [string range $ip_list 0 [expr $startpos + 8000]] # set the end position with the last character as comma * remove last comma set endpos [expr [string last "," $compare_ip_range]-1] # get the actual text range/chunk from the start position to the end position of the whole list set add_ip_range [string range $ip_list $startpos $endpos] # ensure the IP range (chunk) has something in it first if {$add_ip_range !=""} { # add the range of IP's (chunk) to a Windows Firewall Rule if {![catch {exec netsh advfirewall firewall add rule name="IPBlocks" protocol=any dir=in action=block remoteip=$add_ip_range} err]} { } set startpos [expr $endpos+2]; # Update new start position for more chunks +2 characters to skip over removed comma from endpos } }