更新SSL证书验证

服务器更新SSL证书,使用powershell 脚本查看

# ===== 默认值和用户输入 =====
$defaultHost = "www.baidu.com"
$defaultPort = 443

Write-Host "`n===== SSL 证书检查工具 =====`n" -ForegroundColor Cyan
$hostName = Read-Host "请输入主机名或域名 (默认为 $defaultHost, 直接回车使用默认值)"
$portInput = Read-Host "请输入端口号 (默认为 $defaultPort, 直接回车使用默认值)"

# 设置默认主机名
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
    
    # 创建 TCP 客户端连接
    $tcpClient = New-Object System.Net.Sockets.TcpClient
    
    # 设置超时时间为10秒
    $asyncResult = $tcpClient.BeginConnect($hostName, $port, $null, $null)
    $wait = $asyncResult.AsyncWaitHandle.WaitOne(10000, $false)
    
    if (-not $wait) {
        throw "连接超时,服务器无响应"
    }
    
    $tcpClient.EndConnect($asyncResult)
    
    # 创建 SSL 流
    $sslStream = New-Object System.Net.Security.SslStream($tcpClient.GetStream(), $false)
    
    # 设置 SSL 认证超时
    $sslReadTimeout = 10000
    $sslWriteTimeout = 10000
    $sslStream.ReadTimeout = $sslReadTimeout
    $sslStream.WriteTimeout = $sslWriteTimeout
    
    $sslStream.AuthenticateAsClient($hostName, $null, [System.Security.Authentication.SslProtocols]::None, $false) # 使用系统默认协议协商
    
    # 获取远程证书
    if(-not $sslStream.RemoteCertificate) { throw '未获取到服务器证书' }
    $cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]$sslStream.RemoteCertificate
    
    # 计算剩余天数
    $expiryDate = $cert.NotAfter
    $daysLeft = [math]::Max(0, [math]::Round(($expiryDate - (Get-Date)).TotalDays))
    
    # 确定证书状态颜色
    $statusColor = if ($daysLeft -le 7) { "Red" } elseif ($daysLeft -le 30) { "DarkYellow" } else { "Green" }
    
    # 显示结果
    Write-Host "`n`n===== SSL 证书信息 =====`n" -ForegroundColor Cyan
    Write-Host "域名/主机名: $hostName" -ForegroundColor Cyan
    Write-Host "端口: $port"
    Write-Host "主题名称: $($cert.Subject)"
    Write-Host "颁发机构: $($cert.Issuer)"
    Write-Host "生效时间: $($cert.NotBefore.ToLocalTime())"
    Write-Host "到期时间: $($cert.NotAfter.ToLocalTime())" -ForegroundColor $statusColor
    Write-Host "剩余天数: $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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。