Computer >> 컴퓨터 >  >> 체계 >> Windows Server

PowerShell로 SSL/TLS 인증서 만료 날짜 확인하기

서버 인증서가 예기치 않게 만료되면 사용자와 고객에게 여러 가지 문제가 발생할 수 있습니다. 사이트와 보안 연결을 설정할 수 없거나 인증 오류가 발생할 수 있으며 브라우저에 성가신 알림이 표시될 수 있습니다. 이 기사에서는 원격 사이트에서 SSL/TLS 인증서의 만료 날짜를 확인하거나 도메인에 있는 서버 또는 컴퓨터의 로컬 인증서 저장소에서 만료되는 인증서 목록을 가져오는 방법을 보여줍니다.

PowerShell을 사용하여 웹사이트 SSL 인증서의 만료일 가져오기

많은 웹 프로젝트에서 무료 Let's Encrypt SSL 인증서를 사용하여 HTTPS를 구현합니다. 이 인증서는 90에 대한 문제입니다. 일이며 정기적으로 갱신해야 합니다. 일반적으로 특수 스크립트 또는 봇은 호스팅 측 또는 서버 측에서 Let's Encrypt 인증서를 업데이트합니다(Windows의 WACS 또는 Linux의 Certbot일 수 있음). 그러나 자동 인증서 갱신이 실패하는 경우가 있습니다. 웹사이트에서 SSL 인증서 만료 날짜를 확인하고 만료 날짜를 알려주는 스크립트를 갖고 싶습니다. PowerShell을 사용하여 만들었습니다. HttpWeb 쿼리를 통해 웹사이트의 인증서를 확인하고 있기 때문에 원격 웹사이트/서버에 대한 관리자 권한이 필요하지 않습니다.

다음 PowerShell 스크립트에서 인증서 만료 날짜를 확인하려는 웹 사이트 목록과 해당 알림이 표시되기 시작할 때 인증서 기간을 지정해야 합니다($minCertAge ). 예시로 80일을 입력했습니다.

$minCertAge = 80
$timeoutMs = 10000
$sites = @(
"https://testsite1.com/",
"https://testsite2.com/",
"https://woshub.com/"
)
# Disable certificate validation
[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
foreach ($site in $sites)
{
Write-Host Check $site -f Green
$req = [Net.HttpWebRequest]::Create($site)
$req.Timeout = $timeoutMs
try {$req.GetResponse() |Out-Null} catch {Write-Host URL check error $site`: $_ -f Red}
$expDate = $req.ServicePoint.Certificate.GetExpirationDateString()
$certExpDate = [datetime]::ParseExact($expDate, “dd/MM/yyyy HH:mm:ss”, $null)
[int]$certExpiresIn = ($certExpDate - $(get-date)).Days
$certName = $req.ServicePoint.Certificate.GetName()
$certThumbprint = $req.ServicePoint.Certificate.GetCertHashString()
$certEffectiveDate = $req.ServicePoint.Certificate.GetEffectiveDateString()
$certIssuer = $req.ServicePoint.Certificate.GetIssuerName()
if ($certExpiresIn -gt $minCertAge)
{Write-Host The $site certificate expires in $certExpiresIn days [$certExpDate] -f Green}
else
{
$message= "The $site certificate expires in $certExpiresIn days"
$messagetitle= "Renew certificate"
Write-Host $message [$certExpDate]. Details:`n`nCert name: $certName`Cert thumbprint: $certThumbprint`nCert effective date: $certEffectiveDate`nCert issuer: $certIssuer -f Red
#Displays a pop-up notification and sends an email to the administrator
#ShowNotification $messagetitle $message
# Send-MailMessage -From powershell@woshub.com -To admin@woshub.com -Subject $messagetitle -body $message -SmtpServer gwsmtp.woshub.com -Encoding UTF8
}
write-host "________________" `n
}

이 PowerShell 스크립트는 목록에 있는 모든 웹 사이트의 SSL 인증서를 확인합니다. 만료 예정인 인증서가 발견되면 알림에서 강조 표시됩니다.

PowerShell로 SSL/TLS 인증서 만료 날짜 확인하기

SSL 인증서가 곧 만료될 것임을 관리자에게 알리기 위해 팝업 알림을 추가할 수 있습니다. 이를 수행하려면 스크립트 행 "ShowNotification $messagetitle $message의 주석 처리를 제거하십시오. "를 입력하고 다음 기능을 추가합니다.

Function ShowNotification ($MsgTitle, $MsgText) {
Add-Type -AssemblyName System.Windows.Forms
$global:balmsg = New-Object System.Windows.Forms.NotifyIcon
$path = (Get-Process -id $pid).Path
$balmsg.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon($path)
$balmsg.BalloonTipIcon = [System.Windows.Forms.ToolTipIcon]::Warning
$balmsg.BalloonTipText = $MsgText
$balmsg.BalloonTipTitle = $MsgTitle
$balmsg.Visible = $true
$balmsg.ShowBalloonTip(10000)
}

Send-MailMessage를 사용하여 이메일 알림을 보낼 수도 있습니다. .

그런 다음 만료되거나 만료된 인증서가 발견되면 이메일과 팝업 메시지로 알려드립니다.

PowerShell로 SSL/TLS 인증서 만료 날짜 확인하기

그런 다음 작업 스케줄러가 일주일에 한두 번 실행할 자동 작업을 만들고 PowerShell 스크립트를 실행하여 HTTPS 웹 사이트 인증서의 만료 날짜를 확인합니다. (Register-ScheduledTask cmdlet을 사용하여 PS1 스크립트 파일을 실행하는 작업 스케줄러에서 작업을 생성할 수 있습니다.)

Windows 인증서 저장소에서 만료된 인증서를 원격으로 확인하는 방법

또한 도메인 서버(예:RDP/RDS, Exchange, SharePoint, LDAPS 인증서 등) 또는 사용자 컴퓨터의 암호화 서비스에서 사용하는 인증서의 만료 날짜를 확인하는 PowerShell 스크립트가 필요할 수도 있습니다.

로컬 컴퓨터에서 다음 명령을 사용하여 인증서 목록을 가져올 수 있습니다.

Get-ChildItem -Path cert

Powershell 3.0에는 특별한 -ExpiringInDays가 있습니다. 인수:

Get-ChildItem -Path cert: -Recurse -ExpiringInDays 30

PowerShell 2.0에서 동일한 명령은 다음과 같습니다.

Get-ChildItem -Path cert: -Recurse | where { $_.notafter -le (get-date).AddDays(30) -AND $_.notafter -gt (get-date)} | select thumbprint, subject

자신의 인증서만 확인하려면 Cert:\LocalMachine\My를 사용하세요. Cert: 대신 컨테이너 루트 폴더에서. 따라서 Windows에서 신뢰할 수 있는 루트 인증서 및 상업용 인증서를 확인하지 않습니다.

모든 도메인 서버에서 향후 30일 이내에 만료되는 인증서를 찾으려면 다음 PowerShell 스크립트를 사용하십시오.

$servers= (Get-ADComputer -LDAPFilter "(&(objectCategory=computer)(operatingSystem=Windows Server*) (!serviceprincipalname=*MSClusterVirtualServer*) (!(userAccountControl:1.2.840.113556.1.4.803:=2)))").Name
$result=@()
foreach ($server in $servers)
{
$ErrorActionPreference="SilentlyContinue"
$getcert=Invoke-Command -ComputerName $server { Get-ChildItem -Path Cert:\LocalMachine\My -Recurse -ExpiringInDays 30}
foreach ($cert in $getcert) {
$result+=New-Object -TypeName PSObject -Property ([ordered]@{
'Server'=$server;
'Certificate'=$cert.Issuer;
'Expires'=$cert.NotAfter
})
}
}
Write-Output $result

PowerShell로 SSL/TLS 인증서 만료 날짜 확인하기

만료 예정인 서버 인증서 목록이 표시되며 이를 갱신할 충분한 시간이 있습니다.