본문 바로가기
IT

PowerShell을 사용하여 1시간마다 외부 IP, CPU 사용률 및 인터넷 사용률을 이메일로 보내는 스크립트

by 달남 2024. 8. 2.



```powershell
# PowerShell 스크립트

# 이메일 설정
$smtpServer = "smtp.example.com"
$smtpFrom = "your_email@example.com"
$smtpTo = "receiver_email@example.com"
$smtpUser = "your_email@example.com"
$smtpPassword = "your_email_password"

function Get-ExternalIP {
    return (Invoke-RestMethod -Uri "https://api.ipify.org").Trim()
}

function Get-CPUUsage {
    return (Get-WmiObject -Class Win32_Processor).LoadPercentage
}

function Get-InternetUsage {
    $netStats = Get-NetAdapterStatistics | Measure-Object -Property ReceivedBytes, SentBytes -Sum
    return $netStats.Sum.ReceivedBytes + $netStats.Sum.SentBytes
}

function Send-Email {
    param (
        [string]$body
    )
    $msg = New-Object System.Net.Mail.MailMessage
    $msg.From = $smtpFrom
    $msg.To.Add($smtpTo)
    $msg.Subject = "System Status Update"
    $msg.Body = $body

    $client = New-Object Net.Mail.SmtpClient($smtpServer, 587)
    $client.EnableSsl = $true
    $client.Credentials = New-Object System.Net.NetworkCredential($smtpUser, $smtpPassword)
    $client.Send($msg)
}

while ($true) {
    $externalIP = Get-ExternalIP
    $cpuUsage = Get-CPUUsage
    $internetUsage = Get-InternetUsage

    $emailBody = "External IP: $externalIP`nCPU Usage: $cpuUsage%`nInternet Usage: $internetUsage bytes"
    Send-Email -body $emailBody

    Start-Sleep -Seconds 3600 # 1시간 대기
}
```

코드 설명:
1. Get-ExternalIP: 외부 IP를 가져옵니다.
2. Get-CPUUsage: CPU 사용률을 가져옵니다.
3. Get-InternetUsage: 인터넷 사용량을 가져옵니다.
4. Send-Email: 메일을 보내는 기능을 수행합니다.
5. 무한 루프: 1시간마다 정보를 수집하고 메일로 전송합니다.

주의사항:
- 이메일 계정 및 SMTP 서버 정보를 적절히 입력해야 합니다.
- PowerShell 스크립트를 실행할 때 관리자 권한이 필요할 수 있습니다.
- 이 스크립트는 무한 루프를 실행하므로, 중단하려면 수동으로 종료해야 합니다.

댓글