【问题标题】:Firewall Rule update through backend code通过后端代码更新防火墙规则
【发布时间】:2020-06-25 19:59:50
【问题描述】:

我想通过我的 C# 代码更新防火墙规则。我创建了工作正常的 VB 脚本(它以参数为输入)。但是当我通过 C# 代码调用相同的脚本时,防火墙规则没有更新。

请找到我的代码

VB 脚本:

option explicit

' Create the Shell object
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")

' Create the FwPolicy2 object.
Dim fwPolicy2
Set fwPolicy2 = CreateObject("HNetCfg.FwPolicy2")

' Get the Rules object
Dim RulesObject
Set RulesObject = fwPolicy2.Rules

Dim Arg
Set Arg = WScript.Arguments

Dim rule
'Set NewRule=Nothing
Set rule = CreateObject("HNetCfg.FWRule")

For Each rule In Rulesobject
    if rule.Name = "some rule" then
        rule.RemoteAddresses = Arg(0)
        exit for
    end if
next

C#方法:

 string scriptName = @"full path";
                ProcessStartInfo ps = new ProcessStartInfo();
                ps.FileName = "cscript.exe";
                ps.Arguments = string.Format("\"{0}\" \"{1}\"", scriptName, IPRange);
                Process p = new Process();
                p.StartInfo = ps;
                p.Start();
                p.WaitForExit();

【问题讨论】:

    标签: c# vbscript command-line-arguments


    【解决方案1】:

    我从参数列表中删除了双引号,然后它按预期工作。

     ps.Arguments = string.Format("{0} {1}", scriptName, IPRange);
    

    【讨论】:

      【解决方案2】:

      使用 VBScript 执行此操作对我来说看起来很复杂。考虑直接将 C# 与 netsh 一起使用,如下所示:

      // Example firewall rule with settings
      var exampleFirewallRuleName = "My Rule";
      var newRemoteIpAddresses = "127.0.0.1,0.0.0.0,8.8.8.8"; // New list of remote addresses
      
      using (var p = new Process())
      {
          p.StartInfo.FileName = "netsh.exe";
          p.StartInfo.Arguments = string.Format("advfirewall firewall set rule name=\"{0}\" new remoteip={1}", 
              exampleFirewallRuleName, newRemoteIpAddresses);
      
          p.Start();
          p.WaitForExit();
      }
      
      // Run this command in dos prompt to validate:
      // netsh advfirewall firewall show rule name="My Rule"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-23
        • 2015-06-17
        • 2021-04-26
        • 2016-11-26
        • 2022-11-14
        • 1970-01-01
        • 1970-01-01
        • 2021-09-27
        相关资源
        最近更新 更多