由于 Zabbix 自动注册没有删除机制(例如以主机名为规则注册,当服务器主机名变更时,会再次注册,并不删除原主机名的监控),导致有重复项。另外机器下线也需要删除服务器的监控。本文记录一种基于 iTop CMDB 和 Zabbix 接口自动审计 Zabbix 监控服务器的方案。
概述
使用 PHP 语言写脚本,并使用以下 SDK。
1 2 3 4 5 6 |
{ "require": { "ec-europa/itopapi": "^0.5.2", "confirm-it-solutions/php-zabbix-api": "2.4.2" } } |
脚本使用计划任务,每 10 分钟执行一次。
删除下线机器
使用 iTop CMDB API 查询已下线机器列表。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// iTop 中查询所有已下线服务器列表 function getObsoleteServer() { global $iTopAPI; $oql = "SELECT Server WHERE status='obsolete'"; $output_fields = "status,name,hostname"; $data = $iTopAPI->coreGet("Server", $oql, $output_fields); $data = json_decode($data, true); $sn = array(); if($data['objects']) { foreach($data['objects'] as $v) { $sn[] = $v['fields']['name']; } } return $sn; } |
删除操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
// zabbix查询host接口 function zabbixHostGet($name) { global $zbxAPI; $param = array( "output" => array("host","inventory"), "selectInventory" => array("asset_tag", "vendor", "model", "tag", "notes"), "searchInventory" => array("asset_tag" => $name) ); $data = $zbxAPI->hostGet($param); return($data); } // zabbix获取所有有asset_tag的服务器 function zabbixAllHostGet() { return(json_decode(json_encode(zabbixHostGet("")), true)); } // 删除冲突项 及 已下线机器 function main() { global $zbxAPI; $conflict = array(); $obsoleteids = array(); $obsolete = getObsoleteServer(); // 先一次性取出zabbix中所有的host,并组装成key为sn的数组 $zbxServers = zabbixAllHostGet(); $zbxAll = array(); foreach($zbxServers as $server) { $sn = $server['inventory']['asset_tag']; // sn未成功录入inventory的忽略 if($sn == "") { continue; } $hostid = $server['hostid']; if(in_array($sn, $obsolete)) { $obsoleteids[] = $hostid; } if(array_key_exists($sn, $zbxAll)) { array_push($conflict, $hostid, $zbxAll[$sn]['hostid']); }else { $zbxAll[$sn] = $server; } } $ret = array(); $ret['zabbix-count'] = count($zbxServers); foreach($conflict as $host) { $param = array($host); try{ $ret[$host] = $zbxAPI->hostDelete($param); } catch(Exceptioin $e) { $ret[$host] = "failed"; } } try { if($obsoleteids) { $ret['obsolete'] = $zbxAPI->hostDelete($obsoleteids); } } catch(Exceptioin $e) { $ret['obsolete'] = "failed"; } return($ret); } |
后记
实测发现如果 zabbix-agent
未重启,则注册的主机名不会更新。因此 zabbix-agent
需要定时重启。
(全文完)
发表回复