需求描述
在我们的生产环境中,大部分情况下需要有自己的运维体制,包括自己健康状态的检测等。如果发生异常,需要提前预警的,通知形式一般为发邮件告知。
本篇实现
1、每天检查服务器中的SQL Server跑批Job的运行状态,如果跑批失败,则发邮件告诉管理员失败的明细
2、解决多台服务器同时检查
监控脚本
首先我们来解决第二个问题,关于多台服务器的问题:
<1>一般监控我们需要监控很多台服务器的JOb,所以对于服务器的量控制我们需要生成一个配置文件。
<computernames>
<computername>
wuxuelei-pc
</computername>
</computernames>
配置文件名字:computername.xml,这样就解决很多服务器的问题,只需要在配置文件中增加就可以,因为我在本地测试,所以就配置了我的本地电脑
<2>利用Power Shell脚本,抓取出每台服务器的Job的状态,并且将Job的运行时间、运行状态、描述以及错误的步骤等信息整理,形成汇总邮件。
脚本如下:
$server = "(local)" $uid = "sa" $db="master" $pwd="password" $mailprfname = "TestMail" $recipients = "787449667@qq.com" $subject = "老大,快去看看这些服务器的Job跑失败了!" $computernamexml = "F:\PowerShell\发送邮件\computername.xml" function GetServerName($xmlpath) { $xml = [xml] (Get-Content $xmlpath) $return = New-Object Collections.Generic.List[string] for($i = 0;$i -lt $xml.computernames.ChildNodes.Count;$i++) { if ( $xml.computernames.ChildNodes.Count -eq 1) { $cp = [string]$xml.computernames.computername } else { $cp = [string]$xml.computernames.computername[$i] } $return.Add($cp.Trim()) } $return } function GetAlterCounter($xmlpath) { $xml = [xml] (Get-Content $xmlpath) $return = New-Object Collections.Generic.List[string] $list = $xml.counters.Counter } function CreateAlter($message) { $SqlConnection = New-Object System.Data.SqlClient.SqlConnection $CnnString ="Server = $server; Database = $db;User Id = $uid; Password = $pwd" $SqlConnection.ConnectionString = $CnnString $CC = $SqlConnection.CreateCommand(); if (-not ($SqlConnection.State -like "Open")) { $SqlConnection.Open() } $cc.CommandText= " EXEC msdb..sp_send_dbmail @profile_name = '$mailprfname' ,@recipients = '$recipients' ,@body = '$message' ,@subject = '$subject' " $cc.ExecuteNonQuery()|out-null $SqlConnection.Close(); } $report = "" $item = New-Object Collections.Generic.List[string] $names = GetServerName($computernamexml) foreach($cp in $names) { $srv=New-Object "Microsoft.SqlServer.Management.Smo.Server" "(local)" $item=$srv.jobserver.jobs | where-object {$_.lastrunoutcome -eq "Failed" -and $_.isenabled -eq $TRUE} | select OriginatingServer,name,Description,lastrunoutcome,lastrundate,JobSteps #Write-Host $item.JobSteps.name $report += " 服务器:"+$item.OriginatingServer+" Job名称:"+$item.name+" Job描述:"+$item.Description +" Job最后运行状态:"+$item.lastrunoutcome +" Job最后运行时间:"+$item.lastrundate +" Job失败的步骤名称:"+$item.JobSteps.name + "`n" } #生产警告 CreateAlter $report |
通过上述脚本,生成跑批任务,就可以定时监控多台服务器的Job了。
当然,建议放在所有Job的运行完成之后,进行检测。
上述代码中,有两个技术点:
1、需要自己配置SQL Server邮件代理,具体方法参照我上一篇:点击此;
2、需要自己配置跑批计划,方法自己网上搜,很简单。