zabbix通过API创建交换机模板,ifAdminStatus;ifOperStatus;ifInUcastPkts;ifAlias

最终效果:




目的:
        通过zabbix的Latest data查看主机就可以看到其监控结果。

监控项:
        # 管理状态 
        IF-MIB::ifAdminStatus.
        # 操作状态 
        IF-MIB::ifOperStatus.
        # 接收 单播包 
        IF-MIB::ifInUcastPkts.
        # 发送 单播包
        IF-MIB::ifOutUcastPkts.
        # 接收 错误包 
        IF-MIB::ifInErrors.
        # 发送 错误包
        IF-MIB::ifOutErrors.
        # 接收 列队 
        IF-MIB::ifInQLen.
        # 发送 列队
        IF-MIB::ifOutQLen.
        # 接收 多播包 
        IF-MIB::ifInMulticastPkts.
        # 发送 多播包
        IF-MIB::ifOutMulticastPkts.
        # 接收 广播包 
        IF-MIB::ifInBroadcastPkts.
        # 发送 广播包
        IF-MIB::ifOutBroadcastPkts.
       # 接收 非单播包
       IF-MIB::ifInNUcastPkts.
       # 发送 非单播包
       IF-MIB::ifOutNUcastPkts
        # 端口描述 
        IF-MIB::ifAlias.

基础环境:
       centos6.5
       xampp集成环境
       snmpwalk

流程原理:
       通过shell截取snmpwalk出来的index对应端口信息存入MYSQL表内,PHP脚本读取存入MYSQL表内的信息,通过给予的OID名字进行字符串截取生成item名字,KEY,OID创建items,一单items被创建成功,会返回itmeids,脚本讲把这个ID与其他信息存入另一个MYSQL表内。

目录结构:
       snmpwalk.sh               # SNMP信息截取  调用
       insert_snmp_oid.php    # SNMP信息写入  使用
       zbx.inc.php                  #  ZABBIX API     调用
       zbx.templates.class.php   # 创建模板    调用
       usage.php                      # 创建模板    使用

MYSQL表内容

点击(此处)折叠或打开

  1. --
  2. -- 表的结构 `snmp_oid`
  3. --

  4. CREATE TABLE IF NOT EXISTS `snmp_oid` (
  5.   `ID` int(11) NOT NULL AUTO_INCREMENT,
  6.   `IP` varchar(255) NOT NULL,
  7.   `COMMUNITY` varchar(255) NOT NULL,
  8.   `VERSION` varchar(10) DEFAULT NULL,
  9.   `OID_index` varchar(255) NOT NULL,
  10.   `OID_port` varchar(255) NOT NULL,
  11.   `OID_in` varchar(255) NOT NULL,
  12.   `OID_out` varchar(255) NOT NULL,
  13.   PRIMARY KEY (`ID`)
  14. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0 ;

点击(此处)折叠或打开

  1. --
  2. -- 表的结构 `items_plus`
  3. --

  4. CREATE TABLE IF NOT EXISTS `items_plus` (
  5.   `id` int(11) NOT NULL AUTO_INCREMENT,
  6.   `hostid` int(50) NOT NULL,
  7.   `snmp_index` varchar(50) DEFAULT NULL,
  8.   `itemids` int(50) NOT NULL,
  9.   `items_name` varchar(50) DEFAULT NULL,
  10.   `items_key` varchar(50) DEFAULT NULL,
  11.   `items_oid` varchar(50) DEFAULT NULL,
  12.   `ApplicationID` int(10) NOT NULL,
  13.   PRIMARY KEY (`id`)
  14. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0 ;


脚本内容:
 snmpwalk.sh    

点击(此处)折叠或打开

  1. #!/bin/bash

  2. # 迈普交换机设置成 mp
  3. # 锐捷或者华为 随便设定一个值就行。
  4. a="cc"

  5. # 函数

  6. # 生成索引文件
  7. function index() {
  8.     if [ $a == "mp" ];then
  9.         #snmpwalk -$version -c $community $ip IF-MIB::ifDescr |grep 'gi' |awk -F'[ ,=]' '{print $1}' > index.txt
  10.         snmpwalk -$version -c $community $ip IF-MIB::ifDescr |grep 'port' |awk -F'[ ,=]' '{print $1}' > index.txt
  11.     else
  12.         snmpwalk -$version -c $community $ip IF-MIB::ifDescr |grep 'Ethernet' |awk -F'[ ,=]' '{print $1}' > index.txt
  13.     fi
  14. }

  15. # 生成端口名称
  16. function port() {
  17.     if [ $a == "mp" ];then
  18.         #snmpwalk -$version -c $community $ip IF-MIB::ifDescr |grep 'gi' |awk -F'[ ,=]' '{print $5 $6}' > port.txt
  19.         snmpwalk -$version -c $community $ip IF-MIB::ifDescr |grep 'port' |awk -F'[ ,=]' '{print $5 $6}' > port.txt
  20.     else
  21.         snmpwalk -$version -c $community $ip IF-MIB::ifDescr |grep 'Ethernet' |awk -F'[ ,=]' '{print $5 $6}' > port.txt
  22.     fi
  23. }

  24. # 删除生成txt文件
  25. function del(){
  26.     rm -rf ./in.txt out.txt index.txt port.txt
  27. }

  28. # 生成端口流入文件
  29. function _in(){
  30.     if [ -f "index.txt" ];then
  31.         cp ./index.txt in.txt
  32.         
  33.         #SNMP v1
  34.         if [ $version == "v1" ];then
  35.             sed -i "s/IF-MIB::ifDescr/IF-MIB::ifInOctets/g" `grep IF-MIB::ifDescr -rl in.txt `
  36.         fi

  37.         #SNMP v2c
  38.         if [ $version == "v2c" ];then
  39.             sed -i "s/IF-MIB::ifDescr/IF-MIB::ifHCInOctets/g" `grep IF-MIB::ifDescr -rl in.txt `
  40.         fi
  41.  
  42.     else
  43.         echo "not index.txt"
  44.     fi
  45. }

  46. # 生出端口流出文件
  47. function _out(){
  48.     if [ -f "index.txt" ];then
  49.         cp ./index.txt out.txt
  50.        
  51.         #SNMP v1
  52.         if [ $version == "v1" ];then
  53.             sed -i "s/IF-MIB::ifDescr/IF-MIB::ifOutOctets/g" `grep IF-MIB::ifDescr -rl out.txt `
  54.         fi
  55.       
  56.         #SNMP v2c
  57.         if [ $version == "v2c" ];then
  58.             sed -i "s/IF-MIB::ifDescr/IF-MIB::ifHCOutOctets/g" `grep IF-MIB::ifDescr -rl out.txt `
  59.         fi

  60.     else
  61.         echo "not index.txt"
  62.     fi

  63. }

  64. # 外部参数
  65. parameter=$1
  66. community=$3
  67. version=$2
  68. ip=$4

  69. # 参数使用
  70. case $parameter in
  71.     "index")
  72.          index $2 $3 $4 $a
  73.     ;;
  74.     "port")
  75.          port $2 $3 $4 $a
  76.     ;;
  77.     "del")
  78.          del
  79.     ;;
  80.     "in")
  81.          _in $2
  82.     ;;
  83.     "out")
  84.          _out $2
  85.     ;;
  86.     *)
  87.         echo ""
  88.         echo "Usage: {$0 Verison Community Parameter Ip}"
  89.         echo "Parameter: {index|port|del|in|out}"
  90.         echo "Community: {Public}"
  91.         echo "Example: {$0 index v1 Public 202.206.33.37}"
  92.         echo ""
  93.     ;;
  94. esac

insert_snmp_oid.php

点击(此处)折叠或打开

  1. #!/opt/lampp/bin/php
  2. <?php
  3. /*
  4.     使用方法
  5.     chmo +x ./inster_snmp_oid.php
  6.     ./inster_snmp_oid.php v1 stdu.edu.cn_nmc 202.206.32.42
  7. */

  8. /* var */
  9. @@$Version = $argv[1];
  10. @@$Community = $argv[2];
  11. @@$IP = $argv[3];
  12. @@$Factory = $argv[4];

  13. if(isset($Version) && isset($Community) && isset($IP)){
  14.     echo "生成中 ";
  15. }else{
  16.     echo "参数格式:版本,社区名,IP地址 ";
  17.         echo "例子:./inster_snmp_oid.php v1 stdu.edu.cn_nmc 202.206.32.42 ";
  18.     exit;
  19. }

  20. /* PDO mysql */
  21. $pdo = new PDO('mysql:host=202.206.32.218;dbname=test1', 'root', 'zsdsywr.');
  22. $pdo->exec('set names utf8');
  23. $pdo->exec('TRUNCATE TABLE `snmp_oid`');

  24. /* Config */
  25. $Parameter_1 = "index";
  26. $Parameter_2 = "port";
  27. $Parameter_3 = "in";
  28. $Parameter_4 = "out";

  29. /* Shell Script */
  30. function shell($Parameter_1,$Parameter_2,$Parameter_3,$Parameter_4,$Version,$Community,$IP){
  31.    exec("./snmpwalk.sh $Parameter_1 $Version $Community $IP");
  32.    exec("./snmpwalk.sh $Parameter_2 $Version $Community $IP");
  33.    exec("./snmpwalk.sh $Parameter_3 $Version $Community $IP");
  34.    exec("./snmpwalk.sh $Parameter_4 $Version $Community $IP");
  35. }

  36. /* Run Shell */
  37. shell($Parameter_1,$Parameter_2,$Parameter_3,$Parameter_4,$Version,$Community,$IP);

  38. /* Shell Add Files */
  39. $file_index = 'index.txt';
  40. $file_port ='port.txt';
  41. $file_in = 'in.txt';
  42. $file_out = 'out.txt';

  43. /* File Array */
  44. $index = file($file_index);
  45. $port = file($file_port);
  46. $in = file($file_in);
  47. $out = file($file_out);

  48. $sql ="INSERT INTO `snmp_oid`(`ID`,`IP`,`COMMUNITY`,`VERSION`,`OID_index`,`OID_port`,`OID_in`,`OID_out`) VALUES";

  49. foreach ($index as $value1){
  50.    $value2 = current($port);
  51.    $value3 = current($in);
  52.    $value4 = current($out);
  53.  
  54.    $new[] = array("$value1","$value2","$value3","$value4");
  55.    next($port);
  56.    next($in);
  57.    next($out);
  58. }

  59. foreach($new as $value => $key){
  60.   #print_r($key);
  61.   $sql .= "(NULL, '$IP', '$Community', '$Version', '$key[0]','$key[1]','$key[2]','$key[3]'),";
  62. }

  63. $SQL = rtrim($sql,',');
  64. $new_sql = $SQL.";";

  65. $inster = $pdo->exec("$new_sql");

  66. exec("./snmpwalk.sh del");
  67. if($inster == true){
  68.    echo "insert success ";
  69. }else{
  70.     echo "inster error ";
  71. }

zbx.inc.php

点击(此处)折叠或打开

  1. <?php
  2. class jsonrpc{
  3.     
  4.     protected function connect($server, $query){
  5.         $http = curl_init($server);
  6.         curl_setopt($http, CURLOPT_CUSTOMREQUEST, 'POST');
  7.         curl_setopt($http, CURLOPT_POSTFIELDS, $query);
  8.         curl_setopt($http, CURLOPT_RETURNTRANSFER, TRUE);
  9.         curl_setopt($http, CURLOPT_SSL_VERIFYPEER, FALSE);
  10.         /* curl_setopt($http, CURLOPT_PROXY, 'proxy_url');
  11.         curl_setopt($http, CURLOPT_PROXYPORT, '3128');
  12.         curl_setopt($http, CURLOPT_PROXYUSERPWD, 'login:pass'); */
  13.         curl_setopt($http, CURLOPT_SSL_VERIFYHOST, FALSE);
  14.         curl_setopt($http, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
  15.         $response = curl_exec($http);
  16.         return json_decode($response, true);
  17.         curl_close($http);
  18.     }
  19.     
  20. }


  21. class zbx extends jsonrpc{

  22.     public $method;
  23.     public $access_token;
  24.     public $url;
  25.     public $query;

  26.     function call(){
  27.         $data['jsonrpc'] = '2.0';
  28.         $data['method'] = $this->method;
  29.         $data['params'] = $this->query;
  30.         $this->query = '';
  31.         if(!empty($this->access_token))
  32.         $data['auth'] = $this->access_token;
  33.         $data['id'] = rand(1,100);
  34.         $data = json_encode($data, JSON_PRETTY_PRINT);
  35.         return $this->connect($this->url, $data);
  36.     }
  37.         
  38. }

zbx.templates.class.php

点击(此处)折叠或打开

  1. #!/opt/lampp/bin/php
  2. <?php
  3. /**
  4. *交换机snmp模板创建
  5. *
  6. *用于创建zabbix模板的items trigger
  7. * @author kingsh2012@163.com
  8. */

  9. /* Import Zabbix API */
  10. require __DIR__ . '/zbx.inc.php';


  11. class ZabbixTemplates{
  12.     
  13.     /**
  14.     * 构造函数
  15.     * 负责zabbix API调用,与32.218数据库的PDO方式连接。
  16.     *
  17.     * @return $this->zbx;
  18.     * @return $this->pdo;
  19.     */
  20.     function __construct() {
  21.         // zabbix API import
  22.         $this->zbx = new zbx;
  23.         $this->zbx->url = "http://202.206.32.203/api_jsonrpc.php";        //网页地址
  24.         $this->zbx->method = 'user.login';                                
  25.         $this->zbx->query['user'] = 'api';                                //用户名管理员
  26.         $this->zbx->query['password'] = 'zabbix';                        //密码            
  27.         $this->zbx->access_token = $this->zbx->call()['result'];

  28.         // connect 202.206.32.218 databases
  29.         try {
  30.             $this->pdo = new PDO("mysql:host=202.206.32.218;dbname=test1", "root", "zsdsywr.");        //数据库连接
  31.             $this->pdo->exec('set names utf8');
  32.             $sql = "SELECT * FROM `snmp_oid` ";
  33.             // $sql = "SELECT * FROM `items_plus` ";
  34.             $this->snmp = $this->pdo->query($sql);
  35.             }catch (PDOException $e) {
  36.                 exit($e->getMessage());
  37.             }
  38.     }
  39.     
  40.     
  41.     /**
  42.     * GetTemplateID
  43.     * 获取模板ID
  44.     *
  45.     * @access public
  46.     * @param string $name 模板名称
  47.     * @return integer
  48.     */
  49.     function GetTemplateID ($name) {
  50.         $this->zbx->method = 'template.get';
  51.         $this->zbx->query['output'] = 'extend';
  52.         $this->zbx->query['filter']['host'] = "$name";
  53.         @$templateid = $this->zbx->call()['result'][0]['templateid'];
  54.         if(!empty($templateid)){
  55.             return $templateid;
  56.         }else{
  57.             echo "输入主机错误";
  58.         }
  59.     }
  60.     
  61.     /**
  62.     * GetHostID
  63.     * 获取主机ID
  64.     *
  65.     * @access public
  66.     * @param string $host 主机名称
  67.     * @return integer
  68.     */
  69.     function GetHostID ($host) {
  70.         $this->zbx->method = 'host.get';
  71.         $this->zbx->query['output'] = 'extend';
  72.         $this->zbx->query['filter']['host'] = "$host";
  73.         $hostid = $this->zbx->call();
  74.         return $hostid;
  75.     }
  76.     
  77.     /**
  78.     * GetApplicationID
  79.     * 获取应用ID
  80.     *
  81.     * @access 调试
  82.     */     
  83.     function GetApplicationID(){
  84.         $this->zbx->method = 'application.get';
  85.         $this->zbx->query['output'] = 'extend';
  86.         $this->zbx->query['hostids']['host'] = "11562";
  87.         $result = $this->zbx->call();
  88.         print_r($result);
  89.     }
  90.     
  91.     /**
  92.     * DeltetItem
  93.     * 删除items
  94.     *
  95.     * @access 调试
  96.     */     
  97.     function DeltetItem(){
  98.         // $i = 0;
  99.         // foreach($this->snmp as $key => $value ){
  100.             // $itmsids = $value["itemids"];
  101.             // echo $itmsids;
  102.             // exit;
  103.             $this->zbx->method = 'item.delete';
  104.             // $this->zbx->query = ["$itmsids"];
  105.             $this->zbx->query = ['85668'];
  106.             $result = $this->zbx->call();
  107.             print_r($result);
  108.             // echo $i++." ";
  109.             // print_r($value);
  110.             // echo $value["itemids"];
  111.         // }
  112.     }
  113.     
  114.     /**
  115.     * GetHostID
  116.     * 获取主机ID
  117.     *
  118.     * @access public
  119.     * @param string $host 主机名称
  120.     * @return integer
  121.     */
  122.     function GetGroupID($GroupNmae){
  123.         $this->zbx->method = 'hostgroup.get';
  124.         $this->zbx->query['output'] = 'extend';
  125.         $this->zbx->query['filter']['name'] = "$GroupNmae";
  126.         @$groupid = $this->zbx->call()['result']['0']['groupid'];
  127.         if(isset($groupid)){
  128.             return $groupid;
  129.         }else{
  130.             echo $GroupNmae . "你输入的组不存在 ";
  131.             exit;
  132.         }
  133.     }
  134.     
  135.     /**
  136.     * CreateTemplate
  137.     * 创建模板
  138.     *
  139.     * @access public
  140.     * @param string $GroupNmae 以存在的 组名称
  141.     * @param string $TemplateNmae 不存在的 模板名称
  142.     * @return integer
  143.     */
  144.     function CreateTemplate($GroupNmae,$TemplateNmae){
  145.         
  146.         $groupid = $this->GetGroupID($GroupNmae);
  147.         // echo $groupid;
  148.         // exit;
  149.         $this->zbx->method = 'template.create';
  150.         $this->zbx->query['host'] = "$TemplateNmae";
  151.         $this->zbx->query['groups']['groupid'] = "$groupid";
  152.         @$templateids = $this->zbx->call()['result']['templateids']['0'];
  153.         if(isset($templateids)){
  154.             return $templateids;
  155.         }else{
  156.             echo $TemplateNmae . "模板已经存在 ";
  157.             exit;
  158.         }
  159.     }
  160.     
  161.     /**
  162.     * CreateApplication
  163.     * 创建应用
  164.     * 这个很重要,在 Zabbix Latest data里面相当于items的分组
  165.     *
  166.     * @access public
  167.     * @param integer $hostid Application创建在哪个主机下面.主机ID
  168.     * @param integer $number 不同的数字对应着不同的Application名字
  169.     * @return integer
  170.     */
  171.     function CreateApplication($hostid,$number){
  172.         if($number == 1){
  173.             $name = '端口列队';
  174.         }elseif($number == 2){
  175.             $name = '端口单播包';
  176.         }elseif($number == 3){
  177.             $name = '端口多播包';
  178.         }elseif($number == 4){
  179.             $name = '端口广播包';
  180.         }elseif($number == 5){
  181.             $name = '端口描述';
  182.         }elseif($number == 6){
  183.             $name = '端口操作状态';
  184.         }elseif($number == 7){
  185.             $name = '端口流量';
  186.         }elseif($number == 8){
  187.             $name = '端口管理状态';
  188.         }elseif($number == 9){
  189.             $name = '端口错误包';
  190.         }elseif($number == 10){
  191.             $name = '端口非单播包';
  192.         }else{
  193.             echo "应用ID输入错误 ";
  194.             exit;
  195.         }
  196.         $this->zbx->method = 'application.create';
  197.         $this->zbx->query['name'] = "$name";
  198.         $this->zbx->query['hostid'] = "$hostid";
  199.         $applicationids = $this->zbx->call()['result']['applicationids']['0'];
  200.         return $applicationids;
  201.     }
  202.     
  203.     /**
  204.     * CreateItem
  205.     * 创建itme
  206.     *
  207.     * @access public
  208.     * @param integer $type                各种item的选择
  209.     * @param integer $hostid            主机ID
  210.     * @param string $items_name            名字
  211.     * @param string $snmp_version        snmp版本
  212.     * @param string $items_key            KEY
  213.     * @param string $items_oid            OID
  214.     * @param string $snmp_community        社区名
  215.     * @param string $applications        应用ID
  216.     * @param string $description        备注
  217.     * @return integer
  218.     */
  219.     function CreateItem($type, $hostid, $items_name, $snmp_version, $items_key, $items_oid, $snmp_community, $applications,$description){
  220.         // 数据包 双向OID
  221.         if($type == 0){
  222.             $this->zbx->method = 'item.create';
  223.             $this->zbx->query['hostid'] = "$hostid"; //主机号
  224.             $this->zbx->query['name'] = "$items_name"; //items名字
  225.             $this->zbx->query['type'] = "$snmp_version"; //snmp版本号
  226.             $this->zbx->query['key_'] = "$items_key"; //itmes值
  227.             $this->zbx->query['snmp_oid'] = "$items_oid"; //oid
  228.             $this->zbx->query['snmp_community'] = "$snmp_community"; //snmp社区
  229.             $this->zbx->query['port'] = '161'; //端口
  230.             $this->zbx->query['value_type'] = '3'; //3 - numeric unsigned; 数值 特殊
  231.             $this->zbx->query['delay'] = '60';
  232.             $this->zbx->query['applications'] = ["$applications"]; //应用ID
  233.             $this->zbx->query['history'] = '7'; //记录时间 天
  234.             $this->zbx->query['description'] = "$description"; //描述
  235.             $this->zbx->query['delta'] = '1'; //1 - Delta, speed per second; 特殊
  236.             $itemids = $this->zbx->call()['result']['itemids']['0'];
  237.             return $itemids;
  238.         }elseif($type == 1){
  239.             // 流量 双向OID 这个被单独拿了出来是因为流量的涉及到 单位换算 显示单位 差值
  240.             // 注意 其实这个流量生成不建议使用这个函数    有单独对流量做过完整脚本
  241.             $this->zbx->method = 'item.create';
  242.             $this->zbx->query['hostid'] = "$hostid";
  243.             $this->zbx->query['name'] = "$items_name";
  244.             $this->zbx->query['type'] = "$snmp_version";
  245.             $this->zbx->query['key_'] = "$items_key";
  246.             $this->zbx->query['snmp_oid'] = "$items_oid";
  247.             $this->zbx->query['snmp_community'] = "$snmp_community";
  248.             $this->zbx->query['port'] = '161';
  249.             $this->zbx->query['value_type'] = '3';
  250.             $this->zbx->query['delay'] = '60';
  251.             $this->zbx->query['applications'] = ["$applications"];
  252.             $this->zbx->query['history'] = '7';
  253.             $this->zbx->query['description'] = "$description";
  254.             $this->zbx->query['delta'] = '1';
  255.             $this->zbx->query['formula'] = '8'; //特殊
  256.             $this->zbx->query['multiplier'] = '1'; //特殊
  257.             $this->zbx->query['units'] = 'bps'; //特殊
  258.             $itemids = $this->zbx->call()['result']['itemids']['0'];
  259.             return $itemids;
  260.         }elseif($type == 2){
  261.             // 单项 OID
  262.             $this->zbx->method = 'item.create';
  263.             $this->zbx->query['hostid'] = "$hostid";
  264.             $this->zbx->query['name'] = "$items_name";
  265.             $this->zbx->query['type'] = "$snmp_version";
  266.             $this->zbx->query['key_'] = "$items_key";
  267.             $this->zbx->query['snmp_oid'] = "$items_oid";
  268.             $this->zbx->query['snmp_community'] = "$snmp_community";
  269.             $this->zbx->query['port'] = '161';
  270.             $this->zbx->query['value_type'] = '1'; //特殊
  271.             $this->zbx->query['delay'] = '60';
  272.             $this->zbx->query['applications'] = ["$applications"];
  273.             $this->zbx->query['history'] = '7';
  274.             $this->zbx->query['description'] = "$description";
  275.             $itemids = $this->zbx->call()['result']['itemids']['0'];
  276.             return $itemids;
  277.         }elseif($type == 3){
  278.             // 单项OID 管理状态 这个被单独拿了出来是因为"Show value"这个项,在官方的API里面没有找到怎么取这个值. Value mapping
  279.             // 这个item被创建以后返回值是 1-3 (1=up,2=down,3=testing)
  280.             $this->zbx->method = 'item.create';
  281.             $this->zbx->query['hostid'] = "$hostid";
  282.             $this->zbx->query['name'] = "$items_name";
  283.             $this->zbx->query['type'] = "$snmp_version";
  284.             $this->zbx->query['key_'] = "$items_key";
  285.             $this->zbx->query['snmp_oid'] = "$items_oid";
  286.             $this->zbx->query['snmp_community'] = "$snmp_community";
  287.             $this->zbx->query['port'] = '161';
  288.             $this->zbx->query['value_type'] = '1';
  289.             $this->zbx->query['delay'] = '60';
  290.             $this->zbx->query['applications'] = ["$applications"];
  291.             $this->zbx->query['history'] = '7';
  292.             $this->zbx->query['description'] = "$description";
  293.             $this->zbx->query['valuemapid'] = '11'; //特殊
  294.             $itemids = $this->zbx->call()['result']['itemids']['0'];
  295.             return $itemids;
  296.         }elseif($type == 4){
  297.             // 单项OID 操作状态 这个被单独拿了出来是因为"Show value"这个项,在官方的API里面没有找到怎么取这个值. Value mapping
  298.             // 这个item被创建以后返回值是 1-7 (1=up,2=down,3=testing,4=unknown,5=dormant,6=notPresent,7=lowerLayerDown)
  299.             $this->zbx->method = 'item.create';
  300.             $this->zbx->query['hostid'] = "$hostid";
  301.             $this->zbx->query['name'] = "$items_name";
  302.             $this->zbx->query['type'] = "$snmp_version";
  303.             $this->zbx->query['key_'] = "$items_key";
  304.             $this->zbx->query['snmp_oid'] = "$items_oid";
  305.             $this->zbx->query['snmp_community'] = "$snmp_community";
  306.             $this->zbx->query['port'] = '161';
  307.             $this->zbx->query['value_type'] = '1';
  308.             $this->zbx->query['delay'] = '60';
  309.             $this->zbx->query['applications'] = ["$applications"];
  310.             $this->zbx->query['history'] = '7';
  311.             $this->zbx->query['description'] = "$description";
  312.             $this->zbx->query['valuemapid'] = '8'; //特殊
  313.             $itemids = $this->zbx->call()['result']['itemids']['0'];
  314.             return $itemids;
  315.         }
  316.     }
  317.     
  318.     /**
  319.     * Usage_CreateTwoOID
  320.     * 执行函数 创建双OID
  321.     *
  322.     * @access public
  323.     * @param string $GroupNmae            组名称
  324.     * @param string $TemplateNmae        新建模板名称
  325.     * @param string $oid                OID
  326.     * @param integer $applications        应用ID
  327.     * @param integer $type                item类型选择
  328.     * @param string $description        描述
  329.     * @return integer
  330.     */
  331.     function Usage_CreateOneOID($GroupNmae, $TemplateNmae, $oid, $applications, $type, $description){
  332.         
  333.         if(!isset($GroupNmae) || !isset($TemplateNmae) || !isset($oid) || !isset($applications) || !isset($type) || !isset($description)){
  334.             echo "################################################################################################### ";
  335.             echo "# 说明: $a->Pkts('组名称','模板名称','oid','应用ID','类型ID','描述'); # ";
  336.             echo "# 使用: $a->Pkts('华为交换机2326模板','Switch_Quidway_S2326TP-EI','ifAlias',5,2,'端口描述'); # ";
  337.             echo "# 创建应用ID: 输入1-10 # ";
  338.             echo "# 对应关系: 5=端口描述;6=操作状态;8=管理状态 # ";
  339.             echo "# 创建类型ID: 输入2-4 # ";
  340.             echo "# 对应关系: 2=其他;3=管理状态;4=操作状态 # ";
  341.             echo "################################################################################################### ";
  342.             exit();
  343.         }
  344.         
  345.         $TemplateID = $this->CreateTemplate($GroupNmae,$TemplateNmae);
  346.         $ApplicationsID = $this->CreateApplication($TemplateID,$applications);
  347.         $oid_name = str_replace(array('if'), "",$oid);
  348.         
  349.         $insert_sql="INSERT INTO `items_plus`(`id`, `hostid`, `snmp_index`, `itemids`, `items_name`, `items_key`, `items_oid`, `ApplicationID`) VALUES ";

  350.         foreach($this->snmp as $key => $value ){

  351.             if($value['VERSION'] == 'v1'){
  352.                 $snmp_version = "1";
  353.             }elseif($value['VERSION'] == 'v2c'){
  354.                 $snmp_version = "4";
  355.             }
  356.             
  357.             $items = str_replace(array(" ", " ", " "), "", $value['OID_port']);
  358.             $items_name = $items."_$oid_name";
  359.             $items_key = str_replace('/','_',$items_name);
  360.             $items_oid = str_replace('ifDescr',"$oid",$value['OID_index']);
  361.             $items_oid = str_replace(array(" ", " ", " "), "", $items_oid);
  362.             
  363.             $itemids = $this->CreateItem($type, $TemplateID, $items_name, $snmp_version, $items_key, $items_oid, $value['COMMUNITY'], $ApplicationsID,$description);

  364.             $insert_sql .= "(NULL,'$TemplateID','$value[4]','$itemids','$items_name','$items_key','$items_oid','$ApplicationsID'),";
  365.         }
  366.         $insert_sql = rtrim($insert_sql,',');
  367.         $insert_sql = $insert_sql.";";
  368.         $this->pdo->exec("$insert_sql");
  369.     }
  370.     
  371.     /**
  372.     * Usage_CreateTwoOID
  373.     * 执行函数 创建双OID
  374.     *
  375.     * @access public
  376.     * @param string $GroupNmae            组名称
  377.     * @param string $TemplateNmae        新建模板名称
  378.     * @param string $InPkts                接收OID
  379.     * @param string $OutPkts            发送OID
  380.     * @param integer $type                选择item
  381.     * @param integer $applications        应用ID
  382.     * @param string $in_description        接收item描述
  383.     * @param string $out_description    发送item描述
  384.     * @return integer
  385.     */
  386.     function Usage_CreateTwoOID($GroupNmae, $TemplateNmae, $InPkts, $OutPkts, $type, $applications, $in_description,$out_description){

  387.         if(!isset($GroupNmae) || !isset($TemplateNmae) || !isset($InPkts) || !isset($OutPkts) || !isset($type) || !isset($applications) || !isset($in_description) || !isset($out_description)){
  388.             echo "########################################################################################################################### ";
  389.             echo "# 说明: $a->Pkts('组名称', '模板名称', '接收OID', '发送OID', '选择item', '应用ID', '接收OID描述', '发送OID描述'); # ";
  390.             echo "# 使用: $a->Pkts('华为交换机2326模板', 'Switch_Quidway_S2326TP-EI', 'ifInUcastPkts', 'ifOutUcastPkts', 0, 2, '单波包'); # ";
  391.             echo "# type: 输入0-1 # ";
  392.             echo "# 对应关系: 0=其他数据包差值,1=特指流量包; # ";
  393.             echo "# 创建应用ID: 输入1-10 # ";
  394.             echo "# 对应关系: 1=列队;2=单播包;3=多播包;4=广播包;9=错误包;10=非单播包; # ";
  395.             echo "########################################################################################################################### ";
  396.             exit();
  397.         }
  398.         
  399.         $TemplateID = $this->CreateTemplate($GroupNmae,$TemplateNmae);
  400.         $ApplicationsID = $this->CreateApplication($TemplateID,$applications);
  401.         
  402.         $InPkts_name = str_replace(array('ifIn'), "",$InPkts);
  403.         $OutPkts_name = str_replace(array('ifOut'), "",$OutPkts);
  404.         
  405.         $insert_sql="INSERT INTO `items_plus`(`id`, `hostid`, `snmp_index`, `itemids`, `items_name`, `items_key`, `items_oid`, `ApplicationID`) VALUES ";

  406.         foreach($this->snmp as $key => $value ){

  407.             if($value['VERSION'] == 'v1'){
  408.                 $snmp_version = "1";
  409.             }elseif($value['VERSION'] == 'v2c'){
  410.                 $snmp_version = "4";
  411.             }
  412.             
  413.             $items = str_replace(array(" ", " ", " "), "", $value['OID_port']);
  414.             $items_in_name = $items."_in_$InPkts_name";
  415.             $items_in_key = str_replace('/','_',$items_in_name);
  416.             $items_in_oid = str_replace('ifDescr',"$InPkts",$value['OID_index']);
  417.             $items_in_oid = str_replace(array(" ", " ", " "), "", $items_in_oid);

  418.             $items_out_name = $items."_out_$OutPkts_name";
  419.             $items_out_key = str_replace('/','_',$items_out_name);
  420.             $items_out_oid = str_replace('ifDescr',"$OutPkts",$value['OID_index']);
  421.             $items_out_oid = str_replace(array(" ", " ", " "), "", $items_out_oid);
  422.             
  423.             $in_itemids = $this->CreateItem($type, $TemplateID, $items_in_name, $snmp_version, $items_in_key, $items_in_oid, $value['COMMUNITY'], $ApplicationsID,$in_description);
  424.             $out_itemids = $this->CreateItem($type, $TemplateID, $items_out_name, $snmp_version, $items_out_key, $items_out_oid, $value['COMMUNITY'], $ApplicationsID,$out_description);

  425.             $insert_sql .= "(NULL,'$TemplateID','$value[4]','$in_itemids','$items_in_name','$items_in_key','$items_in_oid','$ApplicationsID'),";
  426.             $insert_sql .= "(NULL,'$TemplateID','$value[4]','$in_itemids','$items_out_name','$items_out_key','$items_out_oid','$ApplicationsID'),";
  427.         }
  428.         $insert_sql = rtrim($insert_sql,',');
  429.         $insert_sql = $insert_sql.";";
  430.         $this->pdo->exec("$insert_sql");
  431.     }
  432.     
  433.     /**
  434.     * CreateTrigger
  435.     * 这个函数是创建触发器,但只是创建接收NUcastPkts的触发器
  436.     * 预防广播风暴
  437.     *
  438.     * @access public
  439.     * @param string $HostName            模板名称
  440.     * @return
  441.     */
  442.     function CreateTrigger($HostName){
  443.         $Macros1_1 = '{$NUCASTPKTS_VALUE1}';
  444.         $Macros1_2 = '{$NUCASTPKTS_VALUE2}';
  445.         $Macros1_3 = '{$NUCASTPKTS_VALUE3}';
  446.         $Macros2 = '{$NUCASTPKTS_NAME_HEAD}';
  447.         $Macros3 = '{$NUCASTPKTS_NAME_TAIL}';
  448.         $HostID = $this->GetTemplateID($HostName);
  449.         $sql = "SELECT * FROM `items_plus` WHERE `hostid` = $HostID AND `items_key` LIKE '%in%'";
  450.         $this->items = $this->pdo->query($sql);
  451.         
  452.         $i = 1;
  453.         foreach($this->items as $key => $value ){
  454.             $description_name = str_replace(array(" ", " ", " "), "", $value['items_name']);
  455.             $description_name = str_replace(array('_in_NUcastPkts'), "",$description_name);
  456.             // print_r($description_name);
  457.             
  458.             $this->zbx->method = 'trigger.create';
  459.             $this->zbx->query['description'] = $Macros2 . ' ' . $description_name . " > " . $Macros1_1 .' '. $Macros3;
  460.             $this->zbx->query['expression'] = '{' . $HostName . ':' . $value['items_key'] . ".last(#5)" . '}>' . $Macros1_1;
  461.             $this->zbx->query['priority'] = '1';
  462.             $result1 = $this->zbx->call();
  463.             
  464.             $this->zbx->method = 'trigger.create';
  465.             $this->zbx->query['description'] = $Macros2 . ' ' . $description_name . " > " . $Macros1_2 .' '. $Macros3;
  466.             $this->zbx->query['expression'] = '{' . $HostName . ':' . $value['items_key'] . ".last(#5)" . '}>' . $Macros1_2;
  467.             $this->zbx->query['priority'] = '2';
  468.             $result2 = $this->zbx->call();
  469.             
  470.             $this->zbx->method = 'trigger.create';
  471.             $this->zbx->query['description'] = $Macros2 . ' ' . $description_name . " > " . $Macros1_3 .' '. $Macros3;
  472.             $this->zbx->query['expression'] = '{' . $HostName . ':' . $value['items_key'] . ".last(#5)" . '}>' . $Macros1_3;
  473.             $this->zbx->query['priority'] = '3';
  474.             $result3 = $this->zbx->call();
  475.             echo $i++." ";
  476.         }
  477.     }
  478. }
  479. ?>

usage.php

点击(此处)折叠或打开

  1. #!/opt/lampp/bin/php
  2. <?php
  3. require __DIR__ . '/zbx.templates.class.php';
  4. $ZabbixTemplates = new ZabbixTemplates;
  5. # 华为2326交换机
  6. // $ZabbixTemplates->Usage_CreateOneOID('华为交换机2326模板','Switch_Quidway_S2326TP-EI_Alias','ifAlias',5,2,'端口描述');
  7. // $ZabbixTemplates->Usage_CreateOneOID('华为交换机2326模板','Switch_Quidway_S2326TP-EI_AdminStatus','ifAdminStatus',8,3,'端口管理状态');
  8. // $ZabbixTemplates->Usage_CreateOneOID('华为交换机2326模板','Switch_Quidway_S2326TP-EI_OperStatus','ifOperStatus',6,4,'端口操作状态');
  9. // $ZabbixTemplates->Usage_CreateTwoOID('华为交换机2326模板 ','Switch_Quidway_S2326TP- EI_NUcastPkts','ifInNUcastPkts','ifOutNUcastPkts',0,10,'接收非单波包','发送非单波包 ');
  10. // $ZabbixTemplates->Usage_CreateTwoOID('华为交换机2326模板 ','Switch_Quidway_S2326TP-EI_Errors','ifInErrors','ifOutErrors',0,9,'接收错 误包','发送错误包');
  11. // $ZabbixTemplates->Usage_CreateTwoOID('华为交换机2326模板 ','Switch_Quidway_S2326TP- EI_MulticastPkts','ifInMulticastPkts','ifInMulticastPkts',0,3,'接收多波包','发 送多波包');
  12. // $ZabbixTemplates->Usage_CreateTwoOID('华为交换机2326模板 ','Switch_Quidway_S2326TP- EI_UcastPkts','ifInUcastPkts','ifOutUcastPkts',0,2,'接收单波包','发送单波包');
  13. // $ZabbixTemplates->Usage_CreateTwoOID('华为交换机2326模板 ','Switch_Quidway_S2326TP- EI_BroadcastPkts','ifInBroadcastPkts','ifOutBroadcastPkts',0,4,'接收广波包',' 发送广波包');
  14. // $ZabbixTemplates->Usage_CreateTwoOID('华为交换机2326模板 ','Switch_Quidway_S2326TP-EI_QLen','ifInQLen','ifOutQLen',0,1,'接收列队','发送 列队');
  15. // $ZabbixTemplates->CreateTrigger('Switch_Quidway_S2326TP-EI_NUcastPkts');

注意:
       insert_snmp_oid.php这个文件是操作文件,用来生成SNMP信息。
      usage.php这个文件是导入的操作文件。这个导入只能一次一个的执行这个文件来完成。不能同时导入多个。上边有10个导入,就得执行10次这个文件。
       本人是这样用的,第一开个putty的SSH客户端,打开一个可以支持sftp的编辑器notepad++,putty创建文件加入操作权限,通过notepad++连接centos进行编辑修改。
      为什么要创建这么多的模板?模板关联模板自己想吧。 
      最后的那个itmes_plus表是干什么用的? 存itemids有了这个id,后期再写trigger 和 graphs就比较容易了。
      其实那些OID都是用的OID名字,zabbix支持这种写法。
       为什么TMD用PHP写?因为目前我就会点这语言,以后会重新写成PYTHON的。

原文地址:https://www.cnblogs.com/swordxia/p/4904808.html