代码之家  ›  专栏  ›  技术社区  ›  Didge

用于远程查找IIS中当前绑定的过期证书的Powershell脚本

  •  0
  • Didge  · 技术社区  · 7 年前

    我目前正在编写一个脚本,一旦绑定在我的web服务器IIS中的证书接近到期日期,它就会发送一封电子邮件。我确实有脚本可以通过电子邮件发送。我只需要知道如何将存储查询中可用的证书与当前使用的证书进行比较。现在,我有:

    $Date= (Get-Date)
    $SMTPServer = "smtp.test.com" 
    $From = "testmail@noreply.com"
    
    Import-Module WebAdministration
    
    $Servers = @("WEBSERVER1", "WEBSERVER2")
    
    $certificates = foreach($server in $Servers){
        Invoke-Command -ComputerName $server -ScriptBlock { $CertAll = Get-ChildItem -Path Cert:\LocalMachine\My }
        Invoke-Command -ComputerName $server -ScriptBlock { $CertInUse = Get-ChildItem -Path IIS:\SslBindings }
        Invoke-Command -ComputerName $server -ScriptBlock { $CertSame = Compare-Object -ReferenceObject $CertAll -DifferenceObject $CertInUse -Property Thumbprint -IncludeEqual -ExcludeDifferent }
    
        Invoke-Command -ComputerName $server -ScriptBlock { $cert = $CertSame | ForEach {Get-ChildItem -Path Cert:\LocalMachine\My\$($_.thumbprint)} | 
      Select-Object Subject, DaysUntilExpired, NotAfter, @{n='ExpireInDays';e={($_.notafter - ($Date)).Days}}}
    }
    
        $certificates | Sort DisplayName
    

    如有任何帮助和建议,我们将不胜感激。谢谢

    2 回复  |  直到 7 年前
        1
  •  0
  •   Prasoon Karunan V    7 年前

    当您在同一台计算机的不同会话中创建变量时,上述脚本永远不会工作。

    你可以用两种方法来做。

    1. Invoke-command 执行。

    2. 不创建会话对象,而是通过在单个 Invoke-Command

    Invoke-command -computerName $Server {
        $CertAll = ....
        $CertInUse = ....
        $CertSame = ....
        $cert = $CertSame | ForEach ..... |
        Select-Object Subject, DaysUntilExpired .....
    
    }
    

    如果在确定证书过期日期后,您在远程服务器上没有任何进一步的操作,我建议使用第二个选项。

        2
  •  0
  •   Didge    7 年前

    @我已经设法远程检查了我的证书。我试着在谷歌上找到不同的参考资料。无论如何,这是剧本。

    $Date = Get-Date
    $servers = Get-Content C:\servers.txt
    
    $cert = Foreach ($server in $servers) {
        Invoke-Command -ComputerName $server -ScriptBlock{
            Import-Module WebAdministration; Get-ChildItem -Path IIS:SslBindings | ForEach-Object -Process{
                if ($_.Sites)
                    {
                        $certificate = Get-ChildItem -Path CERT:LocalMachine\My |
                            Where-Object -Property Thumbprint -EQ -Value $_.Thumbprint
    
                        [PSCustomObject]@{
                            Sites = $_.Sites.Value
                            DnsNameList = $certificate.DnsNameList
                            NotAfter = $certificate.NotAfter
                            ExpireInDays = ($certificate.NotAfter - (Get-Date)).Days}
                    }
                } 
            }
        } 
    
    $cert | Select PSComputerName, DnsNameList, NotAfter, ExpireInDays | Where-Object {$_.ExpireInDays -lt 30} | Out-File C:\results.txt
    

    基本上,这将显示证书,证书将在30天内到期。我仍在研究这个问题,因为我试图做的是在脚本检测到证书将在当前日期后30天过期时发送电子邮件,并发送电子邮件通知。我将在另一个帖子中询问我对此的担忧。