close

這個 PowerShell 腳本的用途是自動化更新 IIS 網站的 SSL 憑證。主要功能包括:
1.    下載和讀取 PFX 憑證密碼:
o    從指定的 URL 下載 PFX 憑證的密碼。
2.    下載 PFX 憑證檔案:
o    從指定的 URL 下載 PFX 憑證檔案到本地。
3.    匯入憑證並取得指紋:
o    將 PFX 憑證匯入到本地機器的證書存儲區,並取得匯入憑證的指紋。
4.    獲取所有 IIS 網站名稱和目前 SSL 綁定資訊:
o    獲取所有 IIS 網站名稱,並顯示每個網站當前的 SSL 綁定資訊和憑證指紋。
5.    更新 SSL 綁定:
o    使用新憑證的指紋更新所有使用舊憑證的 SSL 綁定。
6.    檢查 SSL 綁定是否已切換到新憑證:
o    驗證所有網站的 SSL 綁定是否已更新到新的憑證指紋。
7.    刪除本地的 PFX 檔案:
o    刪除下載的臨時 PFX 檔案。
8.    刪除舊憑證:
o    刪除與新憑證不同的舊憑證,以確保只保留最新的憑證。
9.    重新啟動 IIS 服務:
o    重新啟動 IIS 服務以應用新的憑證設定。
10.    刪除腳本本身:
o    在操作完成後刪除腳本本身。
這個腳本實現了自動化的 SSL 憑證更新流程,適用於需要定期更新憑證的 IIS 伺服器環境。

 

# 設置變數
$PFX_FILE_URL = " http://192.168.1.1/123.pfx "
$PASSWORD_URL = " http://192.168.1.1/password.txt"
$TEMP_PFX_PATH = "C:\temp\123pfx"
$SSL_BINDING_IPPORT = "0.0.0.0:443"

function Get-PfxPassword {
    Write-Host "正在從 URL 下載讀取憑證密碼..." -ForegroundColor Cyan
    try {
        $response = Invoke-WebRequest -Uri $PASSWORD_URL
        if ($response.StatusCode -eq 200) {
            $PFX_PASSWORD = [System.Text.Encoding]::UTF8.GetString($response.Content).Trim()
            Write-Host "已成功讀取憑證密碼。" -ForegroundColor Green
            return $PFX_PASSWORD
        } else {
            Write-Host "無法從 URL 下載讀取密碼。 HTTP 狀態碼: $($response.StatusCode)" -ForegroundColor Red
            exit 1
        }
    } catch {
        Write-Host "讀取憑證密碼時發生錯誤: $_" -ForegroundColor Red
        exit 1
    }
}

function Download-PfxFile {
    Write-Host "正在下載 PFX 檔案..." 
    try {
        Invoke-WebRequest -Uri $PFX_FILE_URL -OutFile $TEMP_PFX_PATH
        if (-not (Test-Path $TEMP_PFX_PATH)) {
            Write-Host "無法下載 PFX 檔案。" -ForegroundColor Red
            exit 1
        }
    } catch {
        Write-Host "下載 PFX 檔案時發生錯誤: $_" -ForegroundColor Red
        exit 1
    }
}

function Import-PfxCertificateAndGetThumbprint {
    param (
        [string]$pfxPath,
        [string]$password
    )

    Write-Host "正在匯入憑證並取得指紋..." 
    try {
        $cert = Import-PfxCertificate -FilePath $pfxPath -CertStoreLocation Cert:\LocalMachine\My -Password (ConvertTo-SecureString $password -AsPlainText -Force)
        if (-not $cert) {
            Write-Host "無法匯入憑證。" -ForegroundColor Red
            exit 1
        }
        return $cert.Thumbprint
    } catch {
        Write-Host "匯入憑證時發生錯誤: $_" -ForegroundColor Red
        exit 1
    }
}

function Update-SslBinding {
    param (
        [string]$oldThumbprint,
        [string]$newThumbprint
    )

    Write-Host "正在更新 SSL 綁定..." -ForegroundColor Cyan
    try {
        # 顯示使用舊憑證的綁定
        Get-WebBinding | Where-Object { $_.certificateHash -eq $oldThumbprint } | Format-Table

        # 更新使用舊憑證的綁定
        Get-WebBinding | Where-Object { $_.certificateHash -eq $oldThumbprint } | ForEach-Object {
            Write-Host "正在處理綁定: $_" -ForegroundColor Yellow
            try {
                $_.RemoveSslCertificate()
                $_.AddSslCertificate($newThumbprint, 'My')
                Write-Host "綁定已成功更新。" -ForegroundColor Green
            } catch {
                Write-Host "更新 SSL 綁定時發生錯誤: $_" -ForegroundColor Red
            }
        }
    } catch {
        Write-Host "更新 SSL 綁定時發生錯誤: $_" -ForegroundColor Red
        exit 1
    }
}

function Check-SslBindings {
    Write-Host "檢查 SSL 綁定是否已切換到新憑證..."
    foreach ($site in $sites) {
        Write-Host "正在檢查站台: $($site.Name) ..."
        $bindings = Get-WebBinding -Name $site.Name -Port 443 -Protocol "https" -ErrorAction SilentlyContinue
        if ($bindings) {
            foreach ($binding in $bindings) {
                Write-Host "站台 $($site.Name) 的 SSL 綁定:"
                Write-Host "   協議: $($binding.Protocol)" 
                Write-Host "   憑證指紋:" -NoNewline
                Write-Host $($binding.CertificateHash) -Backgroundcolor red
                Write-Host "   憑證主題: $($binding.CertificateStoreName)"
                Write-Host "   綁定資訊: $($binding.BindingInformation)"
                Write-Host ""
            }
        } else {
            Write-Host "未找到站台 $($site.Name) 的 HTTPS 綁定。"
        }
    }
}

function Remove-OldCertificates {
    Write-Host "正在刪除舊憑證..."
    foreach ($certInfo in $CertificateThumbprints) {
        $existingCert = Get-ChildItem -Path "Cert:\LocalMachine\$($certInfo.StoreName)" | Where-Object { $_.Thumbprint -eq $certInfo }
        if ($existingCert -and $existingCert.Thumbprint -ne $thumbprint) {
            Remove-Item -Path "Cert:\LocalMachine\$($certInfo.StoreName)\$($existingCert.Thumbprint)" -Force -Recurse
            Write-Host "已刪除舊憑證,憑證指紋: $($existingCert.Thumbprint)" -Backgroundcolor Red
        } elseif (-not $existingCert) {
            Write-Host "未找到要刪除的舊憑證,憑證指紋: " -NoNewline
            Write-Host $($certInfo) -ForegroundColor Yellow
        }
    }
}

# 主程式
try {
    $PFX_PASSWORD = Get-PfxPassword
    Start-Sleep -Seconds 3

    Write-Host "正在獲取所有 IIS 站台名稱..."
    $sites = Get-Website

    # 顯示目前 SSL 綁定的憑證資訊並取得憑證指紋
    $CertificateThumbprints = @()
    foreach ($site in $sites) {
        Write-Host "站台: $($site.Name)"
        $bindings = Get-WebBinding -Name $site.Name -Port 443 -Protocol "https" -ErrorAction SilentlyContinue
        if ($bindings) {
            foreach ($binding in $bindings) {
                Write-Host "   協議: $($binding.Protocol)"
                Write-Host "   憑證指紋:" -NoNewline
                Write-Host $($binding.CertificateHash) -Backgroundcolor red
                Write-Host "   憑證主題: $($binding.CertificateStoreName)"
                Write-Host "   綁定資訊: $($binding.BindingInformation)"
                Write-Host ""
                $CertificateThumbprints += $binding.CertificateHash
            }
        } else {
            Write-Host "   未找到 HTTPS 綁定。"
        }
    }

    Download-PfxFile
    $thumbprint = Import-PfxCertificateAndGetThumbprint -pfxPath $TEMP_PFX_PATH -password $PFX_PASSWORD

    Write-Host "匯入的憑證指紋為: " -NoNewline
    Write-Host $thumbprint -Backgroundcolor Red -ForegroundColor Yellow

    # 假設 $OldThumbprint 為舊憑證的指紋
    $OldThumbprint = $CertificateThumbprints[0] # 您可以更具體地選擇哪個是舊指紋
    $NewThumbprint = $thumbprint

    Update-SslBinding -oldThumbprint $OldThumbprint -newThumbprint $NewThumbprint

    Start-Sleep -Seconds 5
    Check-SslBindings

    Write-Host "正在刪除本地的 PFX 檔案..." -ForegroundColor Cyan
    Remove-Item $TEMP_PFX_PATH -Force

    Remove-OldCertificates

    Write-Host "等待操作完成..."
    Start-Sleep -Seconds 5

    Write-Host "正在重新啟動 IIS 服務..." -ForegroundColor Cyan
    Restart-Service W3SVC -Force
    Write-Host "IIS 服務已重新啟動。" -ForegroundColor Green

    Write-Host "完成." -ForegroundColor Green
} catch {
    Write-Host "發生錯誤: $_" -ForegroundColor Red
}

# 查詢目前檔案完整路徑
$currentScriptPath = $MyInvocation.MyCommand.Path
if ($currentScriptPath -ne $null) {
    Write-Host "自動化一鍵 Updating SSL憑證 目前檔案路徑: $currentScriptPath" -ForegroundColor Cyan
} else {
    Write-Host "無法取得目前檔案路徑。"
}

Start-Sleep -Seconds 3

if ($currentScriptPath -ne $null) {
    Remove-Item -Path $currentScriptPath -Force
    Write-Host "自動化一鍵 Updating SSL憑證 腳本自動化檔案已經刪除" -ForegroundColor Cyan
}

Start-Sleep -Seconds 3

 

 

參考資料:

ChatGPT 問答測試結果


arrow
arrow
    文章標籤
    Powershell
    全站熱搜
    創作者介紹
    創作者 sungshu 的頭像
    sungshu

    sungshu手札筆記本

    sungshu 發表在 痞客邦 留言(0) 人氣()