您的位置:首页 > 运维架构 > Shell

Powershell 更新 Nagios Windows客户端

2016-02-04 10:00 543 查看
豆子今天在一个新配置的Nagios服务器上发现对Windows服务器的内存检查仍然使用的是check_nt, check_nt检查的是物理内存和虚拟内存之和;而我需要查看的只是物理内存,因此我需要改成check_nrpe。 Nagios服务器上的配置不多说了,下载安装相关插件,配置command.cfg和windows.cfg, 然后客户端修改对应的NSClient的配置文件,测试通过。

然后问题来了,我有80多台Windows服务器需要修改对应的配置文件,还有10多台Windows服务器根本就没有安装NSClient,我可不想手动去一一安装配置,写了个简单的脚本统一修改。

基本思路,从AD里面获取Windows服务器名字,判断是否在线。对于在线的服务器进行扫描,判断是否安装了NSClient;如果已经安装过的,判断是否已经备份,否则备份之后更新配置文件;如果没有安装的,拷贝安装文件到本地的temp文件夹,进行安装然后更新配置文件。

值得一提的有几点:
1.使用invoke-command远程操作的时候,默认的安全机制会禁止访问网络资源!因此我需要把MSI文件拷贝到本地才能安装。
2.Powershell里面使用msiexec安装msi文件的时候,需要使用start-process 的格式,列如
start-Process -FilePath msiexec.exe -ArgumentList "/i c:\temp\NSCP.msi /q" -Wait -PassThru
如果是远程使用,需要注意第一不能访问网络资源,第二不能使用交互式安装,第三这个MSI文件本身不能创建任何和用户档案相关的文件,比如快捷方式等等;任何一条违反了都会导致失败。

3. 拷贝文件的时候我使用了 copy ... | out-null 的格式,这个作用和 start-process copy.exe -wait 是一样的,都是为了保证当前命令成功结束之后才会进行下一条命令。
4. 这个脚本写的并不完善,比如我没有对有对操作系统是64位或者32位进行判断,也没有异常报错处理等等,我稍后有空进行完善,不过已经可以处理我需要的内容了。

Write-Host "Scanning Online Servers ..."
$a=get-adcomputer -filter {operatingsystem -like "*20*"}
$computers=@()
foreach ($b in $a ){
if(Test-Connection -computername $b.name -Count 1 -Quiet){
$temp=[psobject]@{'name'=$b.name}
$computers+=$temp
}
}
Write-Host "Scanning Nagios Clients ..."
$c2=@()
$computers | ForEach-Object {
$path="\\"+$_.name+"\c$\Program Files\NSClient++\nsclient.ini"
$bakpath="\\"+$_.name+"\c$\Program Files\NSClient++\nsclient.ini.bak"

if ((Test-Path -Path $path) -and !(Test-Path -Path $bakpath))
{

copy $path $bakpath
copy "\\sydav01\c`$\program files\NSClient++\nsclient.ini" $path
#"Restart nscp service on "+$_.name
Invoke-Command -ComputerName $_.name {restart-service nscp}
}else
{
$path + " Folder doesn't Esixt"
$temp=[psobject]@{'name'=$_.name}
$c2+=$temp
}
}
$end=$false
while ( $end -eq $false){
Write-Host "Following servers don't have Nagios Client Installed. "
$c2.name
$option= read-host "Do you want to Install ? ( Y/N ) "
switch($option)
{
"Y"{
$c2| foreach-object {
$path2="\\"+$_.name+"\c$\temp\NSCP.msi"
if( Test-Path $path2){}
else {
New-Item $path2 -Force
}
Write-host "Copying NSCP.msi files to "$path2
copy '\\sydit01\c$\Temp\NSCP-0.4.4.15-x64.msi' $path2 | Out-Null
Write-host "Copying is completed and start to install"
Invoke-Command -ComputerName $_.name -ScriptBlock {
Start-Process -FilePath msiexec.exe -ArgumentList "/i c:\temp\NSCP.msi /q" -Wait -PassThru
}
$path3="\\"+$_.name+"\c$\Program Files\NSClient++\nsclient.ini"
Write-host "Installation is completed and now is updting config file"
copy "\\sydav01\c$\program files\NSClient++\nsclient.ini" $path3
Invoke-Command -ComputerName $_.name {restart-service nscp}
}
$end=$true;
}
"N"{
$end=$true
}
default{
"Please answer Y or N"
}
}
}


运行片段,拷贝文件到某台服务器,安装,更新文件,重启服务




从Nagios服务器上测试成功获取内存信息





本文出自 “麻婆豆腐” 博客,请务必保留此出处http://beanxyz.blog.51cto.com/5570417/1741051
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: