You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chef InSpec的windows_firewall_rule无法识别规则DisplayName如何处理

实现方法

你完全可以在Chef InSpec控制块中先执行Powershell命令获取动态值,再传入测试逻辑使用,具体实现代码如下:

# 执行Powershell命令获取目标防火墙规则的唯一GUID名称,strip去除输出首尾的换行、空白符
firewall_rule_name = powershell('(Get-NetFirewallRule | Where-Object {($_.DisplayName -eq "My Rule") -and ($_.Direction -eq "Inbound")} | Select-Object -First 1).Name').stdout.strip

# 传入动态获取的规则名称执行测试
describe windows_firewall_rule(firewall_rule_name) do
  it { should exist }
  it { should be_enabled }
  it { should be_inbound }
  it { should be_tcp }
  its('local_port') { should eq "5666" }
end

注意事项

  • 命令中加入Select-Object -First 1是为了避免同DisplayName、同方向的规则存在多条时,返回多个值导致测试异常
  • 调用.stdout.strip是为了清理Powershell返回结果自带的换行符、首尾空白,避免传入不符合格式的规则名称
  • 若需要对规则不存在的场景做更友好的提示,可以加一层前置判断:
control 'windows-firewall-rule-001' do
  impact 1.0
  title '检查指定入站防火墙规则配置'
  firewall_rule_name = powershell('(Get-NetFirewallRule | Where-Object {($_.DisplayName -eq "My Rule") -and ($_.Direction -eq "Inbound")} | Select-Object -First 1).Name').stdout.strip

  only_if('目标防火墙规则不存在,跳过测试') do
    !firewall_rule_name.empty?
  end

  describe windows_firewall_rule(firewall_rule_name) do
    it { should exist }
    it { should be_enabled }
    it { should be_inbound }
    it { should be_tcp }
    its('local_port') { should eq "5666" }
  end
end

内容的提问来源于stack exchange,提问作者Lagamorph

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 00:36:00