Last active
December 7, 2015 06:52
-
-
Save GedowFather/ccbc66a39865367a92fe to your computer and use it in GitHub Desktop.
AWS Lambda python script for running zabbix api.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Zabbix API Client. | |
# | |
# Usage: | |
# from modules.ZabbixClient import ZabbixClient | |
# ZABBIX_HOST = "zabbix.example.com" | |
# ZABBIX_PORT = 80 | |
# ZABBIX_USER = 'Admin' | |
# ZABBIX_PASS = 'zabbix' | |
# ZABBIX_PATH = '/api_jsonrpc.php' | |
# ZABBIX_VHOST= 'zabbix.example.com' | |
# client = ZabbixClient( | |
# ZABBIX_HOST, ZABBIX_PORT, | |
# ZABBIX_USER, ZABBIX_PASS, | |
# ZABBIX_PATH, ZABBIX_VHOST, # Optional | |
# ) | |
# METHOD = 'method.name' | |
# PARAMS = {'output': 'hostids', 'filter': {'host': 'client.hostname'} } | |
# result = client.request(METHOD, PARAMS) | |
# | |
import json | |
import urllib2 | |
class ZabbixClient: | |
log = True | |
def __init__(self, host='127.0.0.1', port=80, | |
user='Admin', password='zabbix', | |
path='/api_jsonrpc.php', vhost=None): | |
self.request_id = 1 | |
self.__set_url(host, port, path) | |
self.__set_headers(vhost) | |
self.__get_token(user, password) | |
def __log(self, log): | |
if self.log: print log | |
def __set_url(self, host, port, path): | |
self.url = "http://%s:%d%s" % (host, port, path) | |
def __set_headers(self, vhost=None): | |
self.headers = {'Content-Type': 'application/json-rpc'} | |
if not vhost is None: self.headers['Host'] = vhost | |
def __get_token(self, user, password): | |
self.token = self.request('user.login', {'user': user, 'password': password}) | |
def request(self, method, params): | |
token = self.token if hasattr(self, 'token') else None | |
data = json.dumps({ | |
'jsonrpc': '2.0', | |
'method': method, | |
'params': params, | |
'auth': token, | |
'id': self.request_id, | |
}) | |
self.request_id += 1 | |
try: | |
request = urllib2.Request(self.url, data, self.headers) | |
except: | |
raise Exception("Can't connect server.") | |
try: | |
res = json.loads(urllib2.urlopen(request, timeout=3).read()) | |
except ValueError as e: | |
raise Exception(e) | |
except: | |
raise Exception("Failed API request.") | |
if 'error' in res: raise Exception("Error response (%s)" % (res['error'])) | |
return res['result'] | |
if __name__ == '__main__': | |
client = ZabbixClient('127.0.0.1', 80, 'Admin', 'zabbix', '/api_jsonrpc.php', 'zabbix.gedowfather') | |
print client.request('host.get', {'output': 'hostid', 'limit': 1 }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment