Get information with zabbix api

Challenge to control zabbix api in Python This time I will try to get information

There are pyzabbix etc. which are convenient for Python, but Assuming that there is resistance to installation in the company server environment I tried using json and urllib2 Also, if you can, I think that you will use it after dropping it into a module, I will not do that much this time

Since I am a beginner of Python, I referred to the contents of the predecessor when creating it. [I was allowed to reference] http://www.zumwalt.info/blog/2012/11/pyhtonでzabbix-apiを触ってみる/

Assumed to try this time

--Try to make effective use of remarks (memo writing) with inventory information (I borrowed an idea because my colleague was doing it) --Check if there is any memo (your own memorandum) to share before logging in to the server (it may not be effective because it is a prerequisite to write the memo firmly)

Python script

The operation was confirmed on zabbix 2.0 series and zabbix 2.4 series.

About settings

Please rewrite the url part of client to the address you are listening to Also, don't forget to set http or https

Contents of this time

python


#!/usr/bin/python
# coding: utf-8

import os
import sys
import getpass
import json
import urllib2

if len(sys.argv) != 2 :
  print ' ERROR : Please check Search hostname.'
  print '  Usage: ' + os.path.basename(__file__) + ' [search hostname]'
  sys.exit()

client = 'https://127.0.0.1/zabbix/api_jsonrpc.php'
postheader = {'Content-Type': 'application/json-rpc'}

userid = raw_input('Please Enter Zabbix Web Account : ')
passwd = getpass.getpass('PASSWORD :')
while userid == '':
  print 'type the account.'
  userid = raw_input('Please Enter Zabbix Web Account : ')
while passwd == '':
  print 'type the password'
  passwd = getpass.getpass('PASSWORD :')

# auth
authquery = json.dumps({'jsonrpc':'2.0', 'method':'user.login', 'params':{'user':userid, 'password':passwd}, 'auth':None, 'id': 1})
authreq = urllib2.Request(client, authquery, postheader)

try :
  getauthresult = urllib2.urlopen(authreq).read()
  authresult = json.loads(getauthresult)

except Exception as e :
  print ' %s %s' % ('ERROR :',e)
  print '         Please check zabbix URL Setting or Others.'
  sys.exit()

if 'error' in authresult :
  print ' %s %s' % ('API Error :',authresult['error']['data'])
  sys.exit()

# query
##Methods and parameters
# host.get :Host information acquisition method
# output : Object properties to be returned.If you look at the documentation now, default is extend
# filter : 'status:0' =Monitor-enabled host, 'host:[hogehoge]'Filter by the specified host name
# inventory :Output specification of inventory information item extend=Show all
#If you only want to get the inventory of a specific host, the host of the filter,Only select inventory looks good
postquery = json.dumps({'jsonrpc':'2.0', 'method':'host.get', 'params':{'output':'extend', 'filter':{'status':'0', 'host':sys.argv[1]}, 'selectInventory':'extend'}, 'auth':authresult['result'], 'id':1})
postreq = urllib2.Request(client, postquery, postheader)
getpostresult = urllib2.urlopen(postreq).read()
postresult = json.loads(getpostresult)

# result is empty
if not postresult['result'] :
  print 'no such host.'
  sys.exit()

# result data export
info=[]
for data in postresult['result'] :
  if not data['inventory'] :
    print 'no such inventory .'
    sys.exit()
  info = data['inventory']['notes']

print '--------------------------------------------------'
print '%s%s%s%s%s' % ('# INFO ->  ', sys.argv[1], ' : ', '\n', info)

Execution test

--Prepare an account with each reference authority (Admin is ok) --List inventory information for testing This time we will use remarks (notes) スクリーンショット 2016-10-20 1.19.32.png

--Striking the script $ scriptname.py [Search target host name (set to zabbix)]

python

$ ./get.py test
Please Enter Zabbix Web Account : test
PASSWORD :
--------------------------------------------------
# INFO ->  test :
test test test
Even a test
aaaaaaaaaaa

The output is not good, but you can extract it like this I thought it would be convenient to make it a habit to check every time before logging in to the server, but it is difficult to make rules.

Error when running this script

:If the URL is specified incorrectly:


$ ./get.py test
Please Enter Zabbix Web Account : test
PASSWORD :
 ERROR : <urlopen error [Errno 111] Connection refused>
         Please check zabbix URL Setting or Others.


$ ./get.py test
Please Enter Zabbix Web Account : test
PASSWORD :
 ERROR : HTTP Error 404: Not Found
         Please check zabbix URL Setting or Others.

:Account or password mistake:


$ ./get.py test
Please Enter Zabbix Web Account :a
PASSWORD :
 API Error : Login name or password is incorrect.

:Inventory is disabled, host does not exist (unauthorized and cannot be referenced):


$ ./get.py test1
Please Enter Zabbix Web Account : test
PASSWORD :
no such host.

$ ./get.py test2
Please Enter Zabbix Web Account : test
PASSWORD :
no such inventory.

Of course, you can get various things by changing the method and parameters. Also, I feel that I was able to specify the items to be acquired with selectInventory for this Inventory information. For some reason I remember failing, so I make it extend and process the data

Recommended Posts

Get information with zabbix api
[Python] Get Python package information with PyPI API
Get coincheck virtual currency information with API ♪
Get Alembic information with Python
Get ranking with Rakuten API
[Python] Get user information and article information with Qiita API
Get video file information with ffmpeg-python
[python] Read information with Redmine API
Get weather information with Python & scraping
YOLP Get map information XML file with Yahoo! Static Map API
Collecting information from Twitter with Python (Twitter API)
Get property information by scraping with python
Golang api get
Hit Zabbix API (1.8, 2.0)
Get BITCOIN LTP information with Raspberry PI
Get holidays with the Google Calendar API
I tried to get the movie information of TMDb API with Python
Get the latest AMI information with the AWS CLI
Use the MediaWiki API to get Wiki information
Get stock price data with Quandl API [Python]
Get CPU information of Raspberry Pi with Python
Get Gmail subject and body with Python and Gmail API
Python script to get note information with REAPER
[Linux] Get Linux resource information
[google-oauth] Get user information
Extrude with Fusion360 API
Get started with MicroPython
Get Tweets with Tweepy
Get date with python
Get started with Mezzanine
[Rails] How to get location information using Geolocation API
[First API] Try to get Qiita articles with Python
Get schedule from Garoon SOAP API with Python + Zeep
Get comments and subscribers with the YouTube Data API
Get tweets with arbitrary keywords using Twitter's Streaming API
Get country code with python
Image download with Flickr API
Get table dynamically with sqlalchemy
Use Trello API with python
Get started with Django! ~ Tutorial ⑤ ~
Create an API with Django
Get Twitter timeline with python
Get started with influxDB + Grafana
Use Twitter API with Python
API with Flask + uWSGI + Nginx
Get started with Django! ~ Tutorial ④ ~
Visualize location information with Basemap
Streamline information gathering with the Twitter API and Slack bots
Get started with Django! ~ Tutorial ⑥ ~
Web API with Python + Falcon
Get thread ID with python
Get stock articles of infrastructure engineer yuta with Qiita API
Get GitHub information using PyGithub
Play RocketChat with API / Python
Get YouTube Live chat field in real time with API
Get data from analytics API with Google API Client for python
Support yourself with Twitter API
Zabbix API this and that
Get started with Python! ~ ② Grammar ~
Get image features with OpenCV
Call the API with python3.