最终效果:


目的:
        通过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. #SNMP v1
  33. if [ $version == "v1" ];then
  34. sed -i "s/IF-MIB::ifDescr/IF-MIB::ifInOctets/g" `grep IF-MIB::ifDescr -rl in.txt `
  35. fi
  36. #SNMP v2c
  37. if [ $version == "v2c" ];then
  38. sed -i "s/IF-MIB::ifDescr/IF-MIB::ifHCInOctets/g" `grep IF-MIB::ifDescr -rl in.txt `
  39. fi
  40. else
  41. echo "not index.txt"
  42. fi
  43. }
  44. # 生出端口流出文件
  45. function _out(){
  46. if [ -f "index.txt" ];then
  47. cp ./index.txt out.txt
  48. #SNMP v1
  49. if [ $version == "v1" ];then
  50. sed -i "s/IF-MIB::ifDescr/IF-MIB::ifOutOctets/g" `grep IF-MIB::ifDescr -rl out.txt `
  51. fi
  52. #SNMP v2c
  53. if [ $version == "v2c" ];then
  54. sed -i "s/IF-MIB::ifDescr/IF-MIB::ifHCOutOctets/g" `grep IF-MIB::ifDescr -rl out.txt `
  55. fi
  56. else
  57. echo "not index.txt"
  58. fi
  59. }
  60. # 外部参数
  61. parameter=$1
  62. community=$3
  63. version=$2
  64. ip=$4
  65. # 参数使用
  66. case $parameter in
  67. "index")
  68. index $2 $3 $4 $a
  69. ;;
  70. "port")
  71. port $2 $3 $4 $a
  72. ;;
  73. "del")
  74. del
  75. ;;
  76. "in")
  77. _in $2
  78. ;;
  79. "out")
  80. _out $2
  81. ;;
  82. *)
  83. echo ""
  84. echo "Usage: {$0 Verison Community Parameter Ip}"
  85. echo "Parameter: {index|port|del|in|out}"
  86. echo "Community: {Public}"
  87. echo "Example: {$0 index v1 Public 202.206.33.37}"
  88. echo ""
  89. ;;
  90. 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 "生成中\n";
  15. }else{
  16. echo "参数格式:版本,社区名,IP地址\n";
  17. echo "例子:./inster_snmp_oid.php v1 stdu.edu.cn_nmc 202.206.32.42\n";
  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. $new[] = array("$value1","$value2","$value3","$value4");
  54. next($port);
  55. next($in);
  56. next($out);
  57. }
  58. foreach($new as $value => $key){
  59. #print_r($key);
  60. $sql .= "(NULL, '$IP', '$Community', '$Version', '$key[0]','$key[1]','$key[2]','$key[3]'),";
  61. }
  62. $SQL = rtrim($sql,',');
  63. $new_sql = $SQL.";";
  64. $inster = $pdo->exec("$new_sql");
  65. exec("./snmpwalk.sh del");
  66. if($inster == true){
  67. echo "insert success\n";
  68. }else{
  69. echo "inster error\n";
  70. }

zbx.inc.php

点击(此处)折叠或打开

  1. <?php
  2. class jsonrpc{
  3. protected function connect($server, $query){
  4. $http = curl_init($server);
  5. curl_setopt($http, CURLOPT_CUSTOMREQUEST, 'POST');
  6. curl_setopt($http, CURLOPT_POSTFIELDS, $query);
  7. curl_setopt($http, CURLOPT_RETURNTRANSFER, TRUE);
  8. curl_setopt($http, CURLOPT_SSL_VERIFYPEER, FALSE);
  9. /* curl_setopt($http, CURLOPT_PROXY, 'proxy_url');
  10. curl_setopt($http, CURLOPT_PROXYPORT, '3128');
  11. curl_setopt($http, CURLOPT_PROXYUSERPWD, 'login:pass'); */
  12. curl_setopt($http, CURLOPT_SSL_VERIFYHOST, FALSE);
  13. curl_setopt($http, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
  14. $response = curl_exec($http);
  15. return json_decode($response, true);
  16. curl_close($http);
  17. }
  18. }
  19. class zbx extends jsonrpc{
  20. public $method;
  21. public $access_token;
  22. public $url;
  23. public $query;
  24. function call(){
  25. $data['jsonrpc'] = '2.0';
  26. $data['method'] = $this->method;
  27. $data['params'] = $this->query;
  28. $this->query = '';
  29. if(!empty($this->access_token))
  30. $data['auth'] = $this->access_token;
  31. $data['id'] = rand(1,100);
  32. $data = json_encode($data, JSON_PRETTY_PRINT);
  33. return $this->connect($this->url, $data);
  34. }
  35. }

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. * 负责zabbix API调用,与32.218数据库的PDO方式连接。
  15. *
  16. * @return $this->zbx;
  17. * @return $this->pdo;
  18. */
  19. function __construct() {
  20. // zabbix API import
  21. $this->zbx = new zbx;
  22. $this->zbx->url = "http://202.206.32.203/api_jsonrpc.php";        //网页地址
  23. $this->zbx->method = 'user.login';
  24. $this->zbx->query['user'] = 'api';                                //用户名管理员
  25. $this->zbx->query['password'] = 'zabbix';                        //密码
  26. $this->zbx->access_token = $this->zbx->call()['result'];
  27. // connect 202.206.32.218 databases
  28. try {
  29. $this->pdo = new PDO("mysql:host=202.206.32.218;dbname=test1", "root", "zsdsywr.");        //数据库连接
  30. $this->pdo->exec('set names utf8');
  31. $sql = "SELECT * FROM `snmp_oid` ";
  32. // $sql = "SELECT * FROM `items_plus` ";
  33. $this->snmp = $this->pdo->query($sql);
  34. }catch (PDOException $e) {
  35. exit($e->getMessage());
  36. }
  37. }
  38. /**
  39. * GetTemplateID
  40. * 获取模板ID
  41. *
  42. * @access public
  43. * @param string $name 模板名称
  44. * @return integer
  45. */
  46. function GetTemplateID ($name) {
  47. $this->zbx->method = 'template.get';
  48. $this->zbx->query['output'] = 'extend';
  49. $this->zbx->query['filter']['host'] = "$name";
  50. @$templateid = $this->zbx->call()['result'][0]['templateid'];
  51. if(!empty($templateid)){
  52. return $templateid;
  53. }else{
  54. echo "输入主机错误";
  55. }
  56. }
  57. /**
  58. * GetHostID
  59. * 获取主机ID
  60. *
  61. * @access public
  62. * @param string $host 主机名称
  63. * @return integer
  64. */
  65. function GetHostID ($host) {
  66. $this->zbx->method = 'host.get';
  67. $this->zbx->query['output'] = 'extend';
  68. $this->zbx->query['filter']['host'] = "$host";
  69. $hostid = $this->zbx->call();
  70. return $hostid;
  71. }
  72. /**
  73. * GetApplicationID
  74. * 获取应用ID
  75. *
  76. * @access 调试
  77. */
  78. function GetApplicationID(){
  79. $this->zbx->method = 'application.get';
  80. $this->zbx->query['output'] = 'extend';
  81. $this->zbx->query['hostids']['host'] = "11562";
  82. $result = $this->zbx->call();
  83. print_r($result);
  84. }
  85. /**
  86. * DeltetItem
  87. * 删除items
  88. *
  89. * @access 调试
  90. */
  91. function DeltetItem(){
  92. // $i = 0;
  93. // foreach($this->snmp as $key => $value ){
  94. // $itmsids = $value["itemids"];
  95. // echo $itmsids;
  96. // exit;
  97. $this->zbx->method = 'item.delete';
  98. // $this->zbx->query = ["$itmsids"];
  99. $this->zbx->query = ['85668'];
  100. $result = $this->zbx->call();
  101. print_r($result);
  102. // echo $i++."\n";
  103. // print_r($value);
  104. // echo $value["itemids"];
  105. // }
  106. }
  107. /**
  108. * GetHostID
  109. * 获取主机ID
  110. *
  111. * @access public
  112. * @param string $host 主机名称
  113. * @return integer
  114. */
  115. function GetGroupID($GroupNmae){
  116. $this->zbx->method = 'hostgroup.get';
  117. $this->zbx->query['output'] = 'extend';
  118. $this->zbx->query['filter']['name'] = "$GroupNmae";
  119. @$groupid = $this->zbx->call()['result']['0']['groupid'];
  120. if(isset($groupid)){
  121. return $groupid;
  122. }else{
  123. echo $GroupNmae . "你输入的组不存在\n";
  124. exit;
  125. }
  126. }
  127. /**
  128. * CreateTemplate
  129. * 创建模板
  130. *
  131. * @access public
  132. * @param string $GroupNmae 以存在的 组名称
  133. * @param string $TemplateNmae 不存在的 模板名称
  134. * @return integer
  135. */
  136. function CreateTemplate($GroupNmae,$TemplateNmae){
  137. $groupid = $this->GetGroupID($GroupNmae);
  138. // echo $groupid;
  139. // exit;
  140. $this->zbx->method = 'template.create';
  141. $this->zbx->query['host'] = "$TemplateNmae";
  142. $this->zbx->query['groups']['groupid'] = "$groupid";
  143. @$templateids = $this->zbx->call()['result']['templateids']['0'];
  144. if(isset($templateids)){
  145. return $templateids;
  146. }else{
  147. echo $TemplateNmae . "模板已经存在\n";
  148. exit;
  149. }
  150. }
  151. /**
  152. * CreateApplication
  153. * 创建应用
  154. * 这个很重要,在 Zabbix Latest data里面相当于items的分组
  155. *
  156. * @access public
  157. * @param integer $hostid Application创建在哪个主机下面.主机ID
  158. * @param integer $number 不同的数字对应着不同的Application名字
  159. * @return integer
  160. */
  161. function CreateApplication($hostid,$number){
  162. if($number == 1){
  163. $name = '端口列队';
  164. }elseif($number == 2){
  165. $name = '端口单播包';
  166. }elseif($number == 3){
  167. $name = '端口多播包';
  168. }elseif($number == 4){
  169. $name = '端口广播包';
  170. }elseif($number == 5){
  171. $name = '端口描述';
  172. }elseif($number == 6){
  173. $name = '端口操作状态';
  174. }elseif($number == 7){
  175. $name = '端口流量';
  176. }elseif($number == 8){
  177. $name = '端口管理状态';
  178. }elseif($number == 9){
  179. $name = '端口错误包';
  180. }elseif($number == 10){
  181. $name = '端口非单播包';
  182. }else{
  183. echo "应用ID输入错误\n";
  184. exit;
  185. }
  186. $this->zbx->method = 'application.create';
  187. $this->zbx->query['name'] = "$name";
  188. $this->zbx->query['hostid'] = "$hostid";
  189. $applicationids = $this->zbx->call()['result']['applicationids']['0'];
  190. return $applicationids;
  191. }
  192. /**
  193. * CreateItem
  194. * 创建itme
  195. *
  196. * @access public
  197. * @param integer $type                各种item的选择
  198. * @param integer $hostid            主机ID
  199. * @param string $items_name            名字
  200. * @param string $snmp_version        snmp版本
  201. * @param string $items_key            KEY
  202. * @param string $items_oid            OID
  203. * @param string $snmp_community        社区名
  204. * @param string $applications        应用ID
  205. * @param string $description        备注
  206. * @return integer
  207. */
  208. function CreateItem($type, $hostid, $items_name, $snmp_version, $items_key, $items_oid, $snmp_community, $applications,$description){
  209. // 数据包 双向OID
  210. if($type == 0){
  211. $this->zbx->method = 'item.create';
  212. $this->zbx->query['hostid'] = "$hostid"; //主机号
  213. $this->zbx->query['name'] = "$items_name"; //items名字
  214. $this->zbx->query['type'] = "$snmp_version"; //snmp版本号
  215. $this->zbx->query['key_'] = "$items_key"; //itmes值
  216. $this->zbx->query['snmp_oid'] = "$items_oid"; //oid
  217. $this->zbx->query['snmp_community'] = "$snmp_community"; //snmp社区
  218. $this->zbx->query['port'] = '161'; //端口
  219. $this->zbx->query['value_type'] = '3'; //3 - numeric unsigned; 数值 特殊
  220. $this->zbx->query['delay'] = '60';
  221. $this->zbx->query['applications'] = ["$applications"]; //应用ID
  222. $this->zbx->query['history'] = '7'; //记录时间 天
  223. $this->zbx->query['description'] = "$description"; //描述
  224. $this->zbx->query['delta'] = '1'; //1 - Delta, speed per second; 特殊
  225. $itemids = $this->zbx->call()['result']['itemids']['0'];
  226. return $itemids;
  227. }elseif($type == 1){
  228. // 流量 双向OID 这个被单独拿了出来是因为流量的涉及到 单位换算 显示单位 差值
  229. // 注意 其实这个流量生成不建议使用这个函数    有单独对流量做过完整脚本
  230. $this->zbx->method = 'item.create';
  231. $this->zbx->query['hostid'] = "$hostid";
  232. $this->zbx->query['name'] = "$items_name";
  233. $this->zbx->query['type'] = "$snmp_version";
  234. $this->zbx->query['key_'] = "$items_key";
  235. $this->zbx->query['snmp_oid'] = "$items_oid";
  236. $this->zbx->query['snmp_community'] = "$snmp_community";
  237. $this->zbx->query['port'] = '161';
  238. $this->zbx->query['value_type'] = '3';
  239. $this->zbx->query['delay'] = '60';
  240. $this->zbx->query['applications'] = ["$applications"];
  241. $this->zbx->query['history'] = '7';
  242. $this->zbx->query['description'] = "$description";
  243. $this->zbx->query['delta'] = '1';
  244. $this->zbx->query['formula'] = '8'; //特殊
  245. $this->zbx->query['multiplier'] = '1'; //特殊
  246. $this->zbx->query['units'] = 'bps'; //特殊
  247. $itemids = $this->zbx->call()['result']['itemids']['0'];
  248. return $itemids;
  249. }elseif($type == 2){
  250. // 单项 OID
  251. $this->zbx->method = 'item.create';
  252. $this->zbx->query['hostid'] = "$hostid";
  253. $this->zbx->query['name'] = "$items_name";
  254. $this->zbx->query['type'] = "$snmp_version";
  255. $this->zbx->query['key_'] = "$items_key";
  256. $this->zbx->query['snmp_oid'] = "$items_oid";
  257. $this->zbx->query['snmp_community'] = "$snmp_community";
  258. $this->zbx->query['port'] = '161';
  259. $this->zbx->query['value_type'] = '1'; //特殊
  260. $this->zbx->query['delay'] = '60';
  261. $this->zbx->query['applications'] = ["$applications"];
  262. $this->zbx->query['history'] = '7';
  263. $this->zbx->query['description'] = "$description";
  264. $itemids = $this->zbx->call()['result']['itemids']['0'];
  265. return $itemids;
  266. }elseif($type == 3){
  267. // 单项OID 管理状态 这个被单独拿了出来是因为"Show value"这个项,在官方的API里面没有找到怎么取这个值. Value mapping
  268. // 这个item被创建以后返回值是 1-3 (1=up,2=down,3=testing)
  269. $this->zbx->method = 'item.create';
  270. $this->zbx->query['hostid'] = "$hostid";
  271. $this->zbx->query['name'] = "$items_name";
  272. $this->zbx->query['type'] = "$snmp_version";
  273. $this->zbx->query['key_'] = "$items_key";
  274. $this->zbx->query['snmp_oid'] = "$items_oid";
  275. $this->zbx->query['snmp_community'] = "$snmp_community";
  276. $this->zbx->query['port'] = '161';
  277. $this->zbx->query['value_type'] = '1';
  278. $this->zbx->query['delay'] = '60';
  279. $this->zbx->query['applications'] = ["$applications"];
  280. $this->zbx->query['history'] = '7';
  281. $this->zbx->query['description'] = "$description";
  282. $this->zbx->query['valuemapid'] = '11'; //特殊
  283. $itemids = $this->zbx->call()['result']['itemids']['0'];
  284. return $itemids;
  285. }elseif($type == 4){
  286. // 单项OID 操作状态 这个被单独拿了出来是因为"Show value"这个项,在官方的API里面没有找到怎么取这个值. Value mapping
  287. // 这个item被创建以后返回值是 1-7 (1=up,2=down,3=testing,4=unknown,5=dormant,6=notPresent,7=lowerLayerDown)
  288. $this->zbx->method = 'item.create';
  289. $this->zbx->query['hostid'] = "$hostid";
  290. $this->zbx->query['name'] = "$items_name";
  291. $this->zbx->query['type'] = "$snmp_version";
  292. $this->zbx->query['key_'] = "$items_key";
  293. $this->zbx->query['snmp_oid'] = "$items_oid";
  294. $this->zbx->query['snmp_community'] = "$snmp_community";
  295. $this->zbx->query['port'] = '161';
  296. $this->zbx->query['value_type'] = '1';
  297. $this->zbx->query['delay'] = '60';
  298. $this->zbx->query['applications'] = ["$applications"];
  299. $this->zbx->query['history'] = '7';
  300. $this->zbx->query['description'] = "$description";
  301. $this->zbx->query['valuemapid'] = '8'; //特殊
  302. $itemids = $this->zbx->call()['result']['itemids']['0'];
  303. return $itemids;
  304. }
  305. }
  306. /**
  307. * Usage_CreateTwoOID
  308. * 执行函数 创建双OID
  309. *
  310. * @access public
  311. * @param string $GroupNmae            组名称
  312. * @param string $TemplateNmae        新建模板名称
  313. * @param string $oid                OID
  314. * @param integer $applications        应用ID
  315. * @param integer $type                item类型选择
  316. * @param string $description        描述
  317. * @return integer
  318. */
  319. function Usage_CreateOneOID($GroupNmae, $TemplateNmae, $oid, $applications, $type, $description){
  320. if(!isset($GroupNmae) || !isset($TemplateNmae) || !isset($oid) || !isset($applications) || !isset($type) || !isset($description)){
  321. echo "###################################################################################################\n";
  322. echo "# 说明: \$a->Pkts('组名称','模板名称','oid','应用ID','类型ID','描述'); #\n";
  323. echo "# 使用: \$a->Pkts('华为交换机2326模板','Switch_Quidway_S2326TP-EI','ifAlias',5,2,'端口描述'); #\n";
  324. echo "# 创建应用ID: 输入1-10 #\n";
  325. echo "# 对应关系: 5=端口描述;6=操作状态;8=管理状态 #\n";
  326. echo "# 创建类型ID: 输入2-4 #\n";
  327. echo "# 对应关系: 2=其他;3=管理状态;4=操作状态 #\n";
  328. echo "###################################################################################################\n";
  329. exit();
  330. }
  331. $TemplateID = $this->CreateTemplate($GroupNmae,$TemplateNmae);
  332. $ApplicationsID = $this->CreateApplication($TemplateID,$applications);
  333. $oid_name = str_replace(array('if'), "",$oid);
  334. $insert_sql="INSERT
    INTO `items_plus`(`id`, `hostid`, `snmp_index`, `itemids`,
    `items_name`, `items_key`, `items_oid`, `ApplicationID`) VALUES ";
  335. foreach($this->snmp as $key => $value ){
  336. if($value['VERSION'] == 'v1'){
  337. $snmp_version = "1";
  338. }elseif($value['VERSION'] == 'v2c'){
  339. $snmp_version = "4";
  340. }
  341. $items = str_replace(array("\r\n", "\r", "\n"), "", $value['OID_port']);
  342. $items_name = $items."_$oid_name";
  343. $items_key = str_replace('/','_',$items_name);
  344. $items_oid = str_replace('ifDescr',"$oid",$value['OID_index']);
  345. $items_oid = str_replace(array("\r\n", "\r", "\n"), "", $items_oid);
  346. $itemids = $this->CreateItem($type, $TemplateID, $items_name, $snmp_version, $items_key, $items_oid, $value['COMMUNITY'], $ApplicationsID,$description);
  347. $insert_sql .= "(NULL,'$TemplateID','$value[4]','$itemids','$items_name','$items_key','$items_oid','$ApplicationsID'),";
  348. }
  349. $insert_sql = rtrim($insert_sql,',');
  350. $insert_sql = $insert_sql.";";
  351. $this->pdo->exec("$insert_sql");
  352. }
  353. /**
  354. * Usage_CreateTwoOID
  355. * 执行函数 创建双OID
  356. *
  357. * @access public
  358. * @param string $GroupNmae            组名称
  359. * @param string $TemplateNmae        新建模板名称
  360. * @param string $InPkts                接收OID
  361. * @param string $OutPkts            发送OID
  362. * @param integer $type                选择item
  363. * @param integer $applications        应用ID
  364. * @param string $in_description        接收item描述
  365. * @param string $out_description    发送item描述
  366. * @return integer
  367. */
  368. function Usage_CreateTwoOID($GroupNmae, $TemplateNmae, $InPkts, $OutPkts, $type, $applications, $in_description,$out_description){
  369. if(!isset($GroupNmae) || !isset($TemplateNmae) || !isset($InPkts) || !isset($OutPkts) || !isset($type) || !isset($applications) || !isset($in_description) || !isset($out_description)){
  370. echo "###########################################################################################################################\n";
  371. echo "# 说明: \$a->Pkts('组名称', '模板名称', '接收OID', '发送OID', '选择item', '应用ID', '接收OID描述', '发送OID描述'); #\n";
  372. echo "# 使用: \$a->Pkts('华为交换机2326模板', 'Switch_Quidway_S2326TP-EI', 'ifInUcastPkts', 'ifOutUcastPkts', 0, 2, '单波包'); #\n";
  373. echo "# type: 输入0-1 #\n";
  374. echo "# 对应关系: 0=其他数据包差值,1=特指流量包; #\n";
  375. echo "# 创建应用ID: 输入1-10 #\n";
  376. echo "# 对应关系: 1=列队;2=单播包;3=多播包;4=广播包;9=错误包;10=非单播包; #\n";
  377. echo "###########################################################################################################################\n";
  378. exit();
  379. }
  380. $TemplateID = $this->CreateTemplate($GroupNmae,$TemplateNmae);
  381. $ApplicationsID = $this->CreateApplication($TemplateID,$applications);
  382. $InPkts_name = str_replace(array('ifIn'), "",$InPkts);
  383. $OutPkts_name = str_replace(array('ifOut'), "",$OutPkts);
  384. $insert_sql="INSERT
    INTO `items_plus`(`id`, `hostid`, `snmp_index`, `itemids`,
    `items_name`, `items_key`, `items_oid`, `ApplicationID`) VALUES ";
  385. foreach($this->snmp as $key => $value ){
  386. if($value['VERSION'] == 'v1'){
  387. $snmp_version = "1";
  388. }elseif($value['VERSION'] == 'v2c'){
  389. $snmp_version = "4";
  390. }
  391. $items = str_replace(array("\r\n", "\r", "\n"), "", $value['OID_port']);
  392. $items_in_name = $items."_in_$InPkts_name";
  393. $items_in_key = str_replace('/','_',$items_in_name);
  394. $items_in_oid = str_replace('ifDescr',"$InPkts",$value['OID_index']);
  395. $items_in_oid = str_replace(array("\r\n", "\r", "\n"), "", $items_in_oid);
  396. $items_out_name = $items."_out_$OutPkts_name";
  397. $items_out_key = str_replace('/','_',$items_out_name);
  398. $items_out_oid = str_replace('ifDescr',"$OutPkts",$value['OID_index']);
  399. $items_out_oid = str_replace(array("\r\n", "\r", "\n"), "", $items_out_oid);
  400. $in_itemids = $this->CreateItem($type, $TemplateID, $items_in_name, $snmp_version, $items_in_key, $items_in_oid, $value['COMMUNITY'], $ApplicationsID,$in_description);
  401. $out_itemids = $this->CreateItem($type, $TemplateID, $items_out_name, $snmp_version, $items_out_key, $items_out_oid, $value['COMMUNITY'], $ApplicationsID,$out_description);
  402. $insert_sql .= "(NULL,'$TemplateID','$value[4]','$in_itemids','$items_in_name','$items_in_key','$items_in_oid','$ApplicationsID'),";
  403. $insert_sql .= "(NULL,'$TemplateID','$value[4]','$in_itemids','$items_out_name','$items_out_key','$items_out_oid','$ApplicationsID'),";
  404. }
  405. $insert_sql = rtrim($insert_sql,',');
  406. $insert_sql = $insert_sql.";";
  407. $this->pdo->exec("$insert_sql");
  408. }
  409. /**
  410. * CreateTrigger
  411. * 这个函数是创建触发器,但只是创建接收NUcastPkts的触发器
  412. * 预防广播风暴
  413. *
  414. * @access public
  415. * @param string $HostName            模板名称
  416. * @return
  417. */
  418. function CreateTrigger($HostName){
  419. $Macros1_1 = '{$NUCASTPKTS_VALUE1}';
  420. $Macros1_2 = '{$NUCASTPKTS_VALUE2}';
  421. $Macros1_3 = '{$NUCASTPKTS_VALUE3}';
  422. $Macros2 = '{$NUCASTPKTS_NAME_HEAD}';
  423. $Macros3 = '{$NUCASTPKTS_NAME_TAIL}';
  424. $HostID = $this->GetTemplateID($HostName);
  425. $sql = "SELECT * FROM `items_plus` WHERE `hostid` = $HostID AND `items_key` LIKE '%in%'";
  426. $this->items = $this->pdo->query($sql);
  427. $i = 1;
  428. foreach($this->items as $key => $value ){
  429. $description_name = str_replace(array("\r\n", "\r", "\n"), "", $value['items_name']);
  430. $description_name = str_replace(array('_in_NUcastPkts'), "",$description_name);
  431. // print_r($description_name);
  432. $this->zbx->method = 'trigger.create';
  433. $this->zbx->query['description'] = $Macros2 . ' ' . $description_name . " > " . $Macros1_1 .' '. $Macros3;
  434. $this->zbx->query['expression'] = '{' . $HostName . ':' . $value['items_key'] . ".last(#5)" . '}>' . $Macros1_1;
  435. $this->zbx->query['priority'] = '1';
  436. $result1 = $this->zbx->call();
  437. $this->zbx->method = 'trigger.create';
  438. $this->zbx->query['description'] = $Macros2 . ' ' . $description_name . " > " . $Macros1_2 .' '. $Macros3;
  439. $this->zbx->query['expression'] = '{' . $HostName . ':' . $value['items_key'] . ".last(#5)" . '}>' . $Macros1_2;
  440. $this->zbx->query['priority'] = '2';
  441. $result2 = $this->zbx->call();
  442. $this->zbx->method = 'trigger.create';
  443. $this->zbx->query['description'] = $Macros2 . ' ' . $description_name . " > " . $Macros1_3 .' '. $Macros3;
  444. $this->zbx->query['expression'] = '{' . $HostName . ':' . $value['items_key'] . ".last(#5)" . '}>' . $Macros1_3;
  445. $this->zbx->query['priority'] = '3';
  446. $result3 = $this->zbx->call();
  447. echo $i++."\n";
  448. }
  449. }
  450. }
  451. ?>

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的。

zabbix通过API创建交换机模板,ifAdminStatus;ifOperStatus;ifInUcastPkts;ifAlias的更多相关文章

  1. zabbix利用api批量添加item,并且批量配置添加graph

    关于zabbix的API见,zabbixAPI 1item批量添加 我是根据我这边的具体情况来做的,本来想在模板里面添加item,但是看了看API不支持,只是支持在host里面添加,所以我先在一个ho ...

  2. zabbix java api

    zabbix java api zabbix官方的api文档地址:https://www.zabbix.com/documentation/3.0/manual/api Zabbix功能 概观 Zab ...

  3. zabbix利用自带的模板监控mysql数据库

    zabbix利用自带的模板监控mysql数据库 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 有些东西你不会的时候觉得它特别难,但是当你去做的时候就发现如此的简单~zabbix功能 ...

  4. 调用zabbix 分组api

    调用zabbix 分组api,获取分组中主机host信息,并分类保存, #!/usr/bin/env python #coding:utf8 import requests import json i ...

  5. Web Api ——创建WebAPI

    方法在Win10 + VS2017(MVC5)测试通过 1.建立 WebApi项目: 选择菜单 “文件->新建醒目->web ->ASP.NET Web 应用程序” 输入项目名称和位 ...

  6. [水煮 ASP.NET Web API2 方法论](1-5)ASP.NET Web API Scaffolding(模板)

    问题 我们想快速启动一个 ASP.NET Web API 解决方案. 解决方案 APS.NET 模板一开始就支持 ASP.NET Web API.使用模板往我们的项目中添加 Controller,在我 ...

  7. (41)zabbix监控api接口性能及可用性 天气预报api为例

    现在各种应用都走api,例如淘宝,天气预报等手机.pad客户端都是走api的,那么平时也得对这些api做监控了.怎么做呢?zabbix的web监控是不二选择了.今天就以天气预报api作为一个例子. 天 ...

  8. 创建JDBC模板简化代码、JDBC应用的事务管理以及连接池的作用

    一.创建JDBC模板简化代码 一个简单的查询.要做这么一大堆事情,并且还要处理异常,我们不防来梳理一下: 1.获取connection  2.获取statement  3.获取resultset  4 ...

  9. 使用 .NET CORE 创建 项目模板,模板项目,Template

    场景:日常工作中,你可能会碰到需要新建一个全新的解决方案的情况(如公司新起了一个新项目,需要有全新配套的后台程序),如果公司内部基础框架较多.解决方案需要DDD模式等,那么从新起项目到各种依赖引用到能 ...

随机推荐

  1. HTTP Status 500 - org.apache.jasper.JasperException: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException

    HTTP Status 500 - org.apache.jasper.JasperException: com.sun.org.apache.xerces.internal.impl.io.Malf ...

  2. php课程---建立一个简单的下拉列表框

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  3. 深入分析 Java 中的中文编码问题

    登录 (或注册) 中文 IBM 技术主题 软件下载 社区 技术讲座 打印本页面 用电子邮件发送本页面 新浪微博 人人网 腾讯微博 搜狐微博 网易微博 Digg Facebook Twitter Del ...

  4. EmguCV 简单图形绘制

    一.圆 public static void cvCircle( IntPtr img, System.Drawing.Point center, //Center of the circle int ...

  5. [分享]IOS开发-简单实现搜索框显示历史记录的本地缓存及搜索历史每次只能获取到一个的解决方案

    注:原文:http://www.zhimengzhe.com/IOSkaifa/40433.html 1.首先,我们需要对进行过搜索的textField的输入内容进行一个NSUserDefaults的 ...

  6. ngModel

    https://docs.angularjs.org/error/ngModel/numfmt?p0=sa angular.module('myApp', []) .directive('tagLis ...

  7. 降维技术---PCA

    数据计算和结果展示一直是数据挖掘领域的难点,一般情况下,数据都拥有超过三维,维数越多,处理上就越吃力.所以,采用降维技术对数据进行简化一直是数据挖掘工作者感兴趣的方向. 对数据进行简化的好处:使得数据 ...

  8. IIS删除http header信息如Server, X-Powered-By, 和X-AspNet-Version

    响应头信息原始头信息 Cache-Control private Content-Length 78457 Content-Type text/html; charset=utf-8 Date Fri ...

  9. 《Linux内核分析》第七周 可执行程序的装载

    [刘蔚然 原创作品转载请注明出处 <Linux内核分析>MOOC课程http://mooc.study.163.com/course/USTC-1000029000] WEEK SEVEN ...

  10. Metro 页面间跳转报错、打包和安装一个本地的Metro类型应用

    1.模板页面间传值跳转报错误 参照:http://www.cnblogs.com/dagehaoshuang/archive/2012/08/31/2665166.html#2862480 强烈推荐, ...