概述

因为监控系统不给力,想要自己写一个监控windows server的脚本,并且定期通过邮件来提醒我哪些主机有问题。

参考文档:
Get-CimInstance命令文档
WMI namespace权限
GMSA

遇到的问题

  • 如何远程拿到系统监控参数 受《powershell实战》一书启发,核心逻辑是通过Get-ADComputer遍历windows服务器所在的AD OU,通过Get-CimInstance拿到主机的性能参数,所有结果以HTML的形式保存,并通过邮件发送给我。HTML中,以表格形式呈现,可以通过对参数的判断,可以做标黄标红。性能参数包括但不限于:
性能参数 来源WMI Class
OS版本 Win32_OperatngSystem
IP地址 Win32_NetworkAdapterConfiguration
pending reboot 不从WMI class来,通过Invoke-Command远程执行Test-Path命令来验证相应注册表键值是否存在,
注册表键值:HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired
uptime Win32_OperatngSystem中有LastBootTime,和当前时间计算得到
磁盘信息(容量、磁盘读写IO、读写队列) Win32_LogicalDisk、Win32_PerfFormattedData_PerfDisk_LogicalDisk
内存 Win32_PhysicalMemory、Win32_OperatngSystem
cpu Win32_PerfFormattedData_PerfOS_Processor、CIM_Processor
  • 怎么通过HTML呈现监控信息
    参考了CSS Exchange Health Checker的HTML format。

  • 如何用GMSA运行该脚本
    为了避开AD用户账户的password policy(定期修改密码),我打算使用GMSA来运行脚本,需要解决怎么以GMSA来运行定时任务。

    (1) 先要在AD DS上检查KDS root key
    Get-KdsRootKey
    (2) 若不存在,我们需要创建KDS root key
    Add-KdsRootKey -EffectiveImmediately
    (3) 创建好之后,再次确认KDS root key创建成功
    Get-KdsRootKey
    (4) 使用以下命令创建GMSA
    New-ADService -name gMSA_taskschd -DNSHostName FileServer.contoso.com PrincipalsAllowedToRetrieveManagedPassword "gMSA_SVR_group"
    (5) 在成员服务器上,为了允许账户运行脚本,我们需要将账户添加到“log on as a batch job”用户权限分配中。可以通过组策略或者本地策略来完成。路径Computer Configuration->Windows Settings->Security Settings->Local Policies->User Rights Assgin->Log on as a batch job
    (6) 在成员服务器上,创建定时任务,此步骤无法用GUI完成。
    $arg = "-ExecutionPolicy Bypass -NoProfile -File C:\temo\test.ps1"
    $taction = New-ScheduledTaskAction -Execute C:\Windows\System32\WindowsPowerShel\v1.0\powershell.exe -Argument $arg
    $ttime = New-ScheduledTaskTrigger -At "12:00" -Once
    $tprinc = New-ScheduledTaskPrincipal -UserID contoso\gMSA_taskschd$ -LogonType Password
    Register-ScheduledTask gMSA_Test_Task -Action $taction -Trigger $ttime -Principal $tprinc

  • 需要什么权限
    分为远程协议和WMI自身权限,首先远程协议使用的WSMan(WinRM),需要将域账号添加到远程主机的本地Remote Management Users组里,具体实现方式可以通过GPO,Computer Configuration->Policies->Windows Settings->Security Settings->Restrict Groups,在空白处Add Group,选择Remote Management Users,接着选择需要添加到本地Remote Management Users,将需要添加的账号放到其中,可以将一个域用户组加入到里面,后续只要维护这个组的member即可。
    我们的usecase用到的命名空间是root\CIMV2,所以需要在被远程的机器本地CIMV2 namespace添加对应域账号的权限,权限为WBEM_METHOD_EXECUTE, WBEM_ENABLE, WBEM_REMOTE_ACCESS。又因为要查询performance counter需要额外权限,需要加入到远程机器的本地Performance Monitor Users/Performance Log Users组中,添加方式与Remote Management Users相同。
    回头来说如何设置CIMV2 namespace的权限。手工添加,mmc.msc->wmimanagement,右键securities添加相应权限。如果需要批量添加,考虑使用ps脚本+组策略推送运行脚本任务来达成目的。 添加wmi namespace权限脚本