10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PowerShellでサーバーの死活監視

Posted at

監視対象に定期的にPingを打って反応なければメールを送信するスクリプトです。
イベントログにも記録します。

Check-DeadOrAlive.ps1

# 監視対象
[String[]]$addressAp = @('ホスト1','ホスト2',...)

# 間隔
$interleave=180

# イベントログソース
$eventLogSource = "DeadOrAlive"


# メール送信
function Send-Mail( $Subject, $Body ) {
	$MailSv = "メールサーバー"
	$Port = 587
	$Encode = "UTF8"
	$address = "メールアドレス"

	$pwd = "パスワード" | ConvertTo-SecureString -AsPlainText -Force
	$cred = New-Object System.Management.Automation.PSCredential $address,$pwd

	Send-MailMessage `
	    -To $address `
	    -From $address `
	    -SmtpServer $MailSv `
	    -Credential $cred `
	    -Encoding "UTF8" `
	    -Port $Port `
	    -Subject $Subject `
	    -Body $Body 
}

# イベントログソース作成
if ([System.Diagnostics.EventLog]::SourceExists($eventLogSource) -eq $false){
    New-EventLog -LogName Application -Source $eventLogSource
}
 

$dead_or_alive = @{}
for($i = 0; $i -lt $addressAp.Count; $i++) {
	$dead_or_alive.Add($addressAp[$i],'alive')
}

# ping 
while(1){
	for($i = 0; $i -lt $addressAp.Count; $i++) {
		# Pingを実行します。
		$pingAlive = @(Test-Connection -ComputerName $addressAp[$i] -Quiet)

		if ($pingAlive -eq $True) {
			$message = "Check-DeadOrAlive SUCCESS:" + $addressAp[$i]
			echo $message
			Write-EventLog -LogName Application -Source $eventLogSource -EventId 1 -Message $message
			$dead_or_alive[$addressAp[$i]] = 'alive'
		} else {
			if($dead_or_alive[$addressAp[$i]] -eq 'alive'){
				# ログを記録する
				$message = "Check-DeadOrAlive ERROR:" + $addressAp[$i]
				echo $message
				Write-EventLog -LogName Application -Source $eventLogSource -EventId 1 -Message $message
				# メールを送信する
				$subject = $addressAp[$i] + " IS DEAD"
				[String]$date = Get-Date
				$body = $date + "`r`n" + $subject + "`r`nfrom ad.vanpool.lan"
				Send-Mail $subject $body
				$dead_or_alive[$addressAp[$i]] = 'dead'
			}
		}
	}


	# 待機
	Start-Sleep -s $interleave
}

# 終了
Write-EventLog -LogName Application -Source $eventLogSource -EventId 1 -Message "Check-DeadOrAlive: Terminated"

10
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?