服務器更新SSL證書,使用powershell 腳本查看
# ===== 默認值和用戶輸入 =====
$defaultHost = "www.baidu.com"
$defaultPort = 443
Write-Host "`n===== SSL 證書檢查工具 =====`n" -ForegroundColor Cyan
$hostName = Read-Host "請輸入主機名或域名 (默認為 $defaultHost, 直接回車使用默認值)"
$portInput = Read-Host "請輸入端口號 (默認為 $defaultPort, 直接回車使用默認值)"
# 設(shè)置默認主機名
if ([string]::IsNullOrWhiteSpace($hostName)) {
$hostName = $defaultHost
}
# 兼容舊版 PowerShell 的端口解析 (修復三元運算符問題)
$parsedPort = $null
if ([int]::TryParse($portInput, [ref]$parsedPort)) {
$port = $parsedPort
} else {
$port = $defaultPort
}
# ===== 證書檢查腳本 =====
try {
# 顯示連接信息
Write-Host "`n正在連接: $hostName : $port"
Write-Host "請稍候..." -ForegroundColor Yellow
# 創(chuàng)建 TCP 客戶端連接
$tcpClient = New-Object System.Net.Sockets.TcpClient
# 設(shè)置超時時間為10秒
$asyncResult = $tcpClient.BeginConnect($hostName, $port, $null, $null)
$wait = $asyncResult.AsyncWaitHandle.WaitOne(10000, $false)
if (-not $wait) {
throw "連接超時,服務器無響應"
}
$tcpClient.EndConnect($asyncResult)
# 創(chuàng)建 SSL 流
$sslStream = New-Object System.Net.Security.SslStream($tcpClient.GetStream(), $false)
# 設(shè)置 SSL 認證超時
$sslReadTimeout = 10000
$sslWriteTimeout = 10000
$sslStream.ReadTimeout = $sslReadTimeout
$sslStream.WriteTimeout = $sslWriteTimeout
$sslStream.AuthenticateAsClient($hostName, $null, [System.Security.Authentication.SslProtocols]::None, $false) # 使用系統(tǒng)默認協(xié)議協(xié)商
# 獲取遠程證書
if(-not $sslStream.RemoteCertificate) { throw '未獲取到服務器證書' }
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]$sslStream.RemoteCertificate
# 計算剩余天數(shù)
$expiryDate = $cert.NotAfter
$daysLeft = [math]::Max(0, [math]::Round(($expiryDate - (Get-Date)).TotalDays))
# 確定證書狀態(tài)顏色
$statusColor = if ($daysLeft -le 7) { "Red" } elseif ($daysLeft -le 30) { "DarkYellow" } else { "Green" }
# 顯示結(jié)果
Write-Host "`n`n===== SSL 證書信息 =====`n" -ForegroundColor Cyan
Write-Host "域名/主機名: $hostName" -ForegroundColor Cyan
Write-Host "端口: $port"
Write-Host "主題名稱: $($cert.Subject)"
Write-Host "頒發(fā)機構(gòu): $($cert.Issuer)"
Write-Host "生效時間: $($cert.NotBefore.ToLocalTime())"
Write-Host "到期時間: $($cert.NotAfter.ToLocalTime())" -ForegroundColor $statusColor
Write-Host "剩余天數(shù): $daysLeft 天" -ForegroundColor $statusColor
Write-Host "指紋: $($cert.Thumbprint)`n" -ForegroundColor DarkGray
# 清理資源
$sslStream.Close()
$tcpClient.Close()
}
catch {
$errorMsg = if ($_.Exception.InnerException) {
$_.Exception.InnerException.Message
} else {
$_.Exception.Message
}
Write-Host "`n錯誤: $errorMsg`n" -ForegroundColor Red
} finally {
if ($null -ne $sslStream) { $sslStream.Dispose() }
if ($null -ne $tcpClient) { $tcpClient.Close() }
}
pause