繁体   English   中英

从文本文件读取并添加多个防火墙规则

[英]Reading from a text file and adding multiple firewall rules

我创建了一个脚本,该脚本添加了新的防火墙规则,前提是尚未创建一个新规则。 它检查防火墙规则名称以及通信方向。 如果存在相同的防火墙规则名称,以及入站或出站连接,则不会创建该规则。 它从本地计算机上的文本文件读取。

我要完成的工作是通过读取其中包含多个服务器名称的文本文件在此脚本中添加多个防火墙规则。

例如,我试图将4个不同的防火墙规则(2个入站和2个出站)添加到单个服务器,但是我不确定如何执行此操作。

防火墙规则名称

  • k1(TCP-输入)
  • k2(TCP-输出)
  • k3(TCP-输入)
  • k4(TCP-输出)

码:

$Computers = get-Content -Path "C:\temp\kofaxcomputers.txt"            
Write-host "Checking firewall rules now...." -ForegroundColor Cyan

Invoke-Command -ComputerName $Computers {
    $firewallRuleName = "k1 (TCP- In)"

    if (Get-NetFirewallRule | ? {$_.DisplayName -eq $firewallRuleName -and ($_.Direction -eq 'Inbound' -or $_.Direction -eq 'Outbound')}) {
        Write-host "Firewall rule for '$firewallRuleName' already exists, not creating new rule" -ForegroundColor red
    }
    else {
        Write-host "Firewall rule for '$firewallRuleName' does not already exist, creating new rule now..."
        New-NetFirewallRule -DisplayName $firewallRuleName -Direction Inbound -RemoteAddress Any -Action Allow -Protocol TCP -LocalPort 2424

        Write-host "Firewall rule for '$firewallRuleName' created successfully" -ForegroundColor Green
    }
}

如果创建包含所需规则的CSV,则可以使用Import-Csvforeach循环来创建csv中包含的规则。

示例kofaxrules.csv内容:

"Name", "Direction", "Port"
"k1 (TCP- In)", "Inbound", "2424"
"k2 (TCP- Out)", "Outbound", "1212"
"k3 (TCP- In)", "Inbound", "3434"
"k4 (TCP- Out)", "Outbound", "6565"

码:

$Computers = Get-Content -Path "C:\temp\kofaxcomputers.txt"
$Rules = Import-Csv -Path "C:\temp\kofaxrules.csv"

Write-Host "Checking firewall rules now...." -ForegroundColor Cyan

Invoke-Command -ComputerName $Computers -ScriptBlock {
    foreach ($Rule in $Using:Rules) {
        if (Get-NetFirewallRule -DisplayName $Rule.Name -ErrorAction SilentlyContinue) {
            Write-Host "Firewall rule already exists $($Rule.Name)" -ForegroundColor Green
        }
        else {
            Write-Host "Creating Firewall rule: $($Rule.Name)"
            New-NetFirewallRule -DisplayName $Rule.Name -Direction $Rule.Direction -RemoteAddress Any -Action Allow -Protocol TCP -LocalPort $Rule.Port
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM