在try catch

时间:2016-01-13 13:02:19

标签: powershell exception try-catch

我有一个关于脚本下面的脚本检查多个邮件服务器对RBL列表的问题,问题是某些列表(如hostkarma.junkemailfilter.com)有某些答案并不意味着IP实际上被列入黑名单。

所以我想在try..catch函数中添加一个Exception,如果hostkarma.junkemailfilter.com用127.0.2.1回答,则Mailserver没有进入$blacklistedOn

剧本:

Param([string]$IP)

$statusAlive = "ScriptRes:Host is alive:"
$statusDead = "ScriptRes:No answer:"
$statusUnknown     = "ScriptRes:Unknown:"
$statusNotResolved = "ScriptRes:Unknown host:"
$statusOk          = "ScriptRes:Ok:"
$statusBad         = "ScriptRes:Bad:"
$statusBadContents = "ScriptRes:Bad contents:"

$reversedIP = ($IP -split '\.')[3..0] -join '.'

$blacklistServers = @(
  "dnsbl-3.uceprotect.net";
  "dnsbl-2.uceprotect.net";
  "dnsbl-1.uceprotect.net";
  "ix.dnsbl.manitu.net";
  "bl.spamcop.net";
  "bl.spamcannibal.org";
  "b.barracudacentral.org";
  "ips.backscatterer.org";
  "dnsbl.sorbs.net";
  "cbl.abuseat.org";
  "all.spamrats.com";
  "black.uribl.com";
  "multi.surbl.org";
  "multi.uribl.com";
  "truncate.gbudb.net";
  "bl.blocklist.de";
  "dnsbl.inps.de";
  "bl.mailspike.net";
  "bl.spameatingmonkey.net";
  "db.wpbl.info";
  "dnsbl.justspam.org";
  "hostkarma.junkemailfilter.com";
  "mail-abuse.blacklist.jippg.org";
  "psbl.surriel.com";
  "spam.dnsbl.anonmails.de";
  "ubl.unsubscore.com";
  "cblless.anti-spam.org.cn";
  "cblplus.anti-spam.org.cn";
  "spam.pedantic.org";
  "dev.null.dk";
  "blackholes.five-ten-sg.com";
  "spamsources.fabel.dk";
  "zen.spamhaus.org";
  "spamguard.leadmon.net";
  "dialups.visi.com";
  "dnsbl.kempt.net";
  "dnsbl.dronebl.org";
  "no-more-funn.moensted.dk";
  "relays.bl.kundenserver.de";
)

$blacklistedOn = @()

foreach ($server in $blacklistServers) {
    $IPServer = "$reversedIP.$server"

    try {
        $null = [System.Net.Dns]::GetHostEntry($IPServer)
        $blacklistedOn += $server
    } catch { }
}

if ($blacklistedOn.Count -gt 0) {
    # The IP was blacklisted on one or more servers; send your email here.
    # $blacklistedOn is an array of the servers that returned positive results.
    Write-Host "$statusAlive"$blacklistedOn
} else {
    Write-Host "$statusDead"$blacklistedOn
}

1 个答案:

答案 0 :(得分:0)

目前,您的脚本会丢弃主机查找返回的内容。要在返回特定响应时跳过地址,您需要将其分配给变量并在将服务器实际添加到$blacklistedOn之前检查:

try {
    $addr = [Net.Dns]::GetHostEntry($IPServer)
    if (-not ($server -eq 'hostkarma.junkemailfilter.com' -and $addr.AddressList.IPAddressToString -contains '127.0.2.1')) {
      $blacklistedOn += $server
    }
} catch { }