go 自定义zabbix API库

15 篇文章 0 订阅
6 篇文章 0 订阅
/*
filename: zabbix.go
author: gaohaixiang
writetime:20200416
该脚本为定义go使用zabbix API的库文件,使用事将该文件和go库文件放在一起,
否则导入zabbix这个库文件会报错
放入go安装路径下的 src 文件下的新建zabbix的文件夹下
如:C:\Go\src\zabbix\zabbix.go
*/
package zabbix
import (
   "bytes"
   "crypto/tls"
   "encoding/json"
   "errors"
   "fmt"
   "io"
   "log"
   "net/http"
   "os"
   "sync"
   "time"
)

/**
Zabbix and Go's RPC implementations don't play with each other.. at all.
So I've re-created the wheel at bit.
*/
type JsonRPCResponse struct {
   Jsonrpc string      `json:"jsonrpc"`
   Error   ZabbixError `json:"error"`
   Result  interface{} `json:"result"`
   Id      int         `json:"id"`
}

type JsonRPCRequest struct {
   Jsonrpc string      `json:"jsonrpc"`
   Method  string      `json:"method"`
   Params  interface{} `json:"params"`

   // Zabbix 2.0:
   // The "user.login" method must be called without the "auth" parameter
   Auth string `json:"auth,omitempty"`
   Id   int    `json:"id"`
}

type ZabbixError struct {
   Code    int    `json:"code"`
   Message string `json:"message"`
   Data    string `json:"data"`
}

var mutexZabbix = &sync.Mutex{}

func (z *ZabbixError) Error() string {
   return z.Data
}
type ZabbixHost map[string]interface{}

type API struct {
   url    string
   user   string
   passwd string
   id     int
   auth   string
}


const (
   //zabbix 服务器的IP和url
   IP = "0.0.0.0"
   Url = "http://"+IP+"/zabbix"
)
//server, user, passwd string,
func NewAPI(params ...string) (*API, error) {

   if len(params) == 3 && params[0] != "" && params[1] != "" && params[2] != "" {
      return &API{params[0] + "/api_jsonrpc.php", params[1], params[2], 1, ""}, nil
   }
   if len(params) == 1 && params[0] != "" {
      return &API{id: 1, url:Url+ "/api_jsonrpc.php", auth: params[0]}, nil
   }

   return nil, errors.New("new API 参数错误")
}

func (api *API) GetAuth() string {
   return api.auth
}

func (api *API) ZabbixRequest(method string, data interface{}) (JsonRPCResponse, error) {
   // Setup our JSONRPC Request data x
   id := api.id
   api.id = api.id + 1
   jsonobj := JsonRPCRequest{"2.0", method, data, api.auth, id}
   encoded, err := json.Marshal(jsonobj)
   if err != nil {
      return JsonRPCResponse{}, err
   }

   // Setup our HTTP request
   //client := &http.Client{}
   tr := &http.Transport{ //解决x509: certificate signed by unknown authority
      TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
   }
   client := &http.Client{
      Timeout:   30 * time.Second,
      Transport: tr, //解决x509: certificate signed by unknown authority
   }

   request, err := http.NewRequest("POST", api.url, bytes.NewBuffer(encoded))

   if err != nil {
      return JsonRPCResponse{}, err
   }
   request.Header.Add("Content-Type", "application/json-rpc")
   if api.auth != "" {
      // XXX Not required in practice, check spec
      //request.SetBasicAuth(api.user, api.passwd)
      //request.Header.Add("Authorization", api.auth)
   }

   // Execute the request
   response, err := client.Do(request)

   if err != nil {
      return JsonRPCResponse{}, err
   }

   /**
   We can't rely on response.ContentLength because it will
   be set at -1 for large responses that are chunked. So
   we treat each API response as streamed data.
   */
   var result JsonRPCResponse
   var buf bytes.Buffer

   _, err = io.Copy(&buf, response.Body)
   if err != nil {
      return JsonRPCResponse{}, err
   }

   err = json.Unmarshal(buf.Bytes(), &result)
   if err != nil {
      return JsonRPCResponse{}, err
   }

   response.Body.Close()

   return result, nil
}

func (api *API) Login() (bool, error) {
   params := make(map[string]string, 0)
   params["user"] = api.user
   params["password"] = api.passwd

   response, err := api.ZabbixRequest("user.login", params)
   if err != nil {
      fmt.Printf("Error: %s\n", err)
      return false, err
   }

   if response.Error.Code != 0 {
      return false, &response.Error
   }

   api.auth = response.Result.(string)
   return true, nil
}

func (api *API) Version() (string, error) {
   response, err := api.ZabbixRequest("APIInfo.version", make(map[string]string, 0))
   if err != nil {
      return "", err
   }

   if response.Error.Code != 0 {
      return "", &response.Error
   }

   return response.Result.(string), nil
}

/**
Interface to the host.* calls
*/
func (api *API) Host(method string, data interface{}) ([]ZabbixHost, error) {
   response, err := api.ZabbixRequest("host."+method, data)
   if err != nil {
      return nil, err
   }

   if response.Error.Code != 0 {
      return nil, &response.Error
   }

   // XXX uhg... there has got to be a better way to convert the response
   // to the type I want to return
   res, err := json.Marshal(response.Result)
   var ret []ZabbixHost
   err = json.Unmarshal(res, &ret)
   return ret, nil
}

func GetApi() (*API, error) {
   fmt.Println("GetAPI")
   //zbxUrl := beego.AppConfig.String("ZbxUrl")
   //zbxUser := beego.AppConfig.String("ZbxUser")
   //zbxPassword := beego.AppConfig.String("ZbxPassword")
   zbxUrl := ""
   zbxUser := ""
   zbxPassword := ""

   api, _ := NewAPI(zbxUrl+"/api_jsonrpc.php", zbxUser, zbxPassword)
   if ok, err := api.Login(); ok {
      return api, nil
   } else {
      return nil, err
   }
}

//验证sessionid 并返回用户信息
func CheckAuthentication(sessionid string) (JsonRPCResponse, error) {
   params := []string{sessionid}
   api, _ := NewAPI(Url+"/api_jsonrpc.php", "", "")
   response, err := api.ZabbixRequest("user.checkAuthentication", params)
   if err != nil {
      fmt.Printf("Error: %s\n", err)
      return JsonRPCResponse{}, err
   }
   if response.Error.Code != 0 {
      return JsonRPCResponse{}, &response.Error
   }
   return response, nil
}

func FileWrite(content,filename string)  {
   //var filename = "zabbix/zabbix-restult.txt"
   // 以读写方式打开文件,并且内容写入方式为添加,如果文件不存在以0755操作模式创建文件
   f, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0755)
   if err != nil {
      log.Fatal(err)
   }
   // 关闭文件
   defer f.Close()
   if err != nil {
      // 创建文件失败处理
   } else {
      //content := "sdkfjsdfj "
      _, err = f.Write([]byte(content))
      if err != nil {
         // 写入失败处理
      }
   }
}

func ZabbixLogIn(url,user,password,method string,data map[string]interface{}) (res []byte) {
   fmt.Println("start main")
   //NewAPI,ZabbixRequest,Login
   //url := "http://192.168.73.11/api_jsonrpc.php"
   //user := "admin"
   //password := "zabbix"
   api,err := NewAPI(url,user,password)
   fmt.Println(api)
   if err != nil {
      fmt.Println("NewAPI  fail")
   }
   login,err :=api.Login()
   if login {
      //
      fmt.Println("login auth ok")
   }else{
      fmt.Println("login auth fail",err)
   }

   //获取结果
   result,err:=api.ZabbixRequest(method,data)
   if err != nil {
      return
   }
   if result.Error.Code != 0 {
      err = errors.New(result.Error.Message)
      return
   }
   fmt.Println(result)
   //json 转化
   res, err = json.Marshal(result.Result)
   //res, err := json.Marshal(result.Result)
   if err != nil {
      return
   }
   return res
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值