SW/PowerShell / / 2023. 4. 13. 10:45

[검증 완료] 포트 모니터링 파워쉘

반응형

안녕하세요.

 

오늘은 포트 모니터링을 하는 파워쉘을 공유 할까 합니다.

 

powershell port monitoring

 

내용은 아래와 같습니다.

 

간략하게 설명드리자면

 

1. 3389 포트 모니터링 3초에 한번씩 진행 --> 정상이면 3389 포트 확인 성공 출력

2. 3389 포트가 3번 연속 실패하면 --> 이메일로 경고 메일 전송

3. 3389 포트가 다시 정상으로 되면 정상 메일 알림 발송

 

# SMTP 서버 및 포트 설정
$smtpServer = "smtp.office365.com"
$smtpPort = 587

# 보내는 메일 계정 정보
$username = "보내는 메일 주소"
$password = "보내는 메일 비밀번호"

# 받는 메일 주소
$to = "받는 메일주소"

# SMTP 인증 설정
$smtpCred = New-Object System.Management.Automation.PSCredential -ArgumentList $username, (ConvertTo-SecureString -String $password -AsPlainText -Force)

# 포트 모니터링 함수
function Test-Port {
    param (
        [string]$targetHost,
        [int]$port
    )
    $tcpClient = New-Object Net.Sockets.TcpClient
    $connection = $tcpClient.BeginConnect($targetHost, $port, $null, $null)
    $timeout = $connection.AsyncWaitHandle.WaitOne(3000,$false)
    if(!$timeout -or !$tcpClient.Connected) {
        return $false
    }
    $tcpClient.EndConnect($connection) | Out-Null
    $tcpClient.Close()
    return $true
}

# 포트 확인 실패 횟수 초기화
$failedAttempts = 0

# 계속해서 포트 확인 및 이메일 알림
while ($true) {
    # 포트 확인
    $portStatus = Test-Port -targetHost "localhost" -port 3389

    # 포트 확인 실패 시
    if (!$portStatus) {
        $failedAttempts++
        Write-Host "3389 포트 확인 실패 - $failedAttempts 번째 시도"

        # 3번 이상 실패 시
        if ($failedAttempts -ge 3) {
            # 경고 메일 전송
            $body = "3389 포트 확인 결과: 실패 - 3번 이상 실패하였습니다."
            $subject = "3389 Port Alert: Connection Failure"
            Send-MailMessage -To $to -From $username -Subject $subject -Body $body -SmtpServer $smtpServer -Credential $smtpCred -Port $smtpPort -UseSsl -Encoding UTF8

            # 경고 메일 전송 후 초기화
            $failedAttempts = 0
        }
    }
    # 포트 확인 성공 시
    else {
        $failedAttempts = 0
        Write-Host "3389 포트 확인 성공"

        # 정상 메일 전송
        $body = "3389 포트 확인 결과: 성공"
        $subject = "3389 Port Alert: Connection Success"
        Send-MailMessage -To $to -From $username -Subject $subject -Body $body -SmtpServer $smtpServer -Credential $smtpCred -Port $smtpPort -UseSsl
    }

    # 3초 대기
    Start-Sleep -Seconds 3
}

 

반응형
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유