本文整理汇总了Python中zabbix_api.ZabbixAPI类的典型用法代码示例。如果您正苦于以下问题:Python ZabbixAPI类的具体用法?Python ZabbixAPI怎么用?Python ZabbixAPI使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ZabbixAPI类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: main
def main():
"""The main function"""
login = "myatsko"#raw_input("Login: ")
pwd = "[email protected]"#raw_input("Password: ")
zapi = ZabbixAPI('https://zabbix.kernelfire.com/zabbix', login, pwd, r_query_len=100)
zapi.login(login, pwd)
print "Connected to Zabbix API Version %s" % zapi.api_version()
template_id = zapi.template.get({"output": "extend", "search": {"name": 'App RabbitMQ'}})[0]["templateid"]
print "Template ID", template_id
hosts = []
items = {}
gitems = {}
print "Host IDs:"
for rig in zapi.host.get({"templateids":template_id}):
hosts.append(rig["hostid"])
print rig["hostid"], rig["name"]
print "Collecting items and assigning colors to them..."
for i in hosts:
items[i] = zapi.item.get({"hostids": i, "search": {"key_": 'queue_message_stats'}})
gitems[i] = []
for j in items[i]:
gitems[i].append({"itemid": j["itemid"], "color": '%02X%02X%02X' % (rand(), rand(), rand())})
print "Creating graph for", i
try:
zapi.graph.create({"name": "Aggregated queue stats", "width": 900, "height": 300, "gitems": gitems[i]})
except:
print "Graph already exists or cannot be created"
continue
print "All done"
开发者ID:magistersart,项目名称:scripting,代码行数:29,代码来源:Grapher.py
示例2: get_metric
def get_metric(self, host, item, **kwargs):
"""
Returns the last value of "item" from "host"
:param host: hostname of itemholder
:param item: itemname of wanted item
:param kwargs: Optional parameter
:return:
"""
if self.__address is not None:
if 'password' in kwargs:
password = kwargs['password']
else:
password = 'zabbix'
if 'username' in kwargs:
username = kwargs['username']
else:
username = 'admin'
zapi = ZabbixAPI(server='http://'+self.__address+'/zabbix',
path="", log_level=0)
zapi.login(username, password)
hostid = zapi.host.get({"filter": {"host": host}})[0]["hostid"]
item_values = zapi.item.get({"params": {"hostids": hostid},
"filter": {"name": item,
"hostid": hostid}})
return item_values[0]["lastvalue"]
else:
return None
开发者ID:Pentadactylus,项目名称:hurtle_sdk,代码行数:31,代码来源:monitoring.py
示例3: __init__
class zabbix:
def __init__(self,server=None,log_level=0,log=None):
"""
Accepts keyword args for Server and log_level
@type server: str
@param server: Zabbix Server URL
@type log_level: int
@param log_level: Logging level for this class
"""
self.zapi = ZabbixAPI(server=server,log_level=log_level)
if log == None:
self._log = setup_logging()
else:
self._log = log
def login(self,username=None,password=None):
"""
Login handler
"""
try:
self._log.debug("Attempting to login")
self.zapi.login(username,password)
self._log.debug("Login successfull")
except Exception, e:
# Unable to login, lets just bomb out
self._log.error("Failed to login - exiting")
sys.exit()
开发者ID:RackLabs-Zabbix,项目名称:automation,代码行数:30,代码来源:z.py
示例4: __init__
def __init__(self):
self.defaultgroup = 'group_all'
self.zabbix_server = None
self.zabbix_username = None
self.zabbix_password = None
self.read_settings()
self.read_cli()
if self.zabbix_server and self.zabbix_username:
try:
api = ZabbixAPI(server=self.zabbix_server)
api.login(user=self.zabbix_username, password=self.zabbix_password)
except BaseException, e:
print "Error: Could not login to Zabbix server. Check your zabbix.ini."
sys.exit(1)
if self.options.host:
data = self.get_host(api, self.options.host)
print json.dumps(data, indent=2)
elif self.options.list:
data = self.get_list(api)
print json.dumps(data, indent=2)
else:
print "usage: --list ..OR.. --host <hostname>"
sys.exit(1)
开发者ID:BenoitDherin,项目名称:collaboratool,代码行数:29,代码来源:zabbix.py
示例5: __init__
def __init__(self):
self.defaultgroup = 'group_all'
self.zabbix_server = None
self.zabbix_username = None
self.zabbix_password = None
self.read_settings()
self.read_cli()
if self.zabbix_server and self.zabbix_username:
try:
api = ZabbixAPI(server=self.zabbix_server)
api.login(user=self.zabbix_username, password=self.zabbix_password)
except BaseException as e:
print("Error: Could not login to Zabbix server. Check your zabbix.ini.", file=sys.stderr)
sys.exit(1)
if self.options.host:
data = self.get_host(api, self.options.host)
print(json.dumps(data, indent=2))
elif self.options.list:
data = self.get_list(api)
print(json.dumps(data, indent=2))
else:
print("usage: --list ..OR.. --host <hostname>", file=sys.stderr)
sys.exit(1)
else:
print("Error: Configuration of server and credentials are required. See zabbix.ini.", file=sys.stderr)
sys.exit(1)
开发者ID:neditest,项目名称:ansible_zabbix,代码行数:33,代码来源:zabbix.py
示例6: main
def main():
module = AnsibleModule(
argument_spec=dict(
server_url=dict(type='str', required=True, aliases=['url']),
login_user=dict(type='str', required=True),
login_password=dict(type='str', required=True, no_log=True),
http_login_user=dict(type='str',required=False, default=None),
http_login_password=dict(type='str',required=False, default=None, no_log=True),
host_groups=dict(type='list', required=True, aliases=['host_group']),
state=dict(default="present", choices=['present','absent']),
timeout=dict(type='int', default=10)
),
supports_check_mode=True
)
if not HAS_ZABBIX_API:
module.fail_json(msg="Missing requried zabbix-api module (check docs or install with: pip install zabbix-api)")
server_url = module.params['server_url']
login_user = module.params['login_user']
login_password = module.params['login_password']
http_login_user = module.params['http_login_user']
http_login_password = module.params['http_login_password']
host_groups = module.params['host_groups']
state = module.params['state']
timeout = module.params['timeout']
zbx = None
# login to zabbix
try:
zbx = ZabbixAPI(server_url, timeout=timeout, user=http_login_user, passwd=http_login_password)
zbx.login(login_user, login_password)
except Exception, e:
module.fail_json(msg="Failed to connect to Zabbix server: %s" % e)
开发者ID:gmangin,项目名称:ansible-modules-extras,代码行数:35,代码来源:zabbix_group.py
示例7: LoginZabbixServer
def LoginZabbixServer(server, username, password):
try:
zapi = ZabbixAPI(server=server, path="", log_level=6)
zapi.login(username, password)
except ZabbixAPIException, e:
print e
return False, None
开发者ID:DavidXubin,项目名称:zabbix_dev,代码行数:8,代码来源:zabbix_api_wrapper.py
示例8: api_connect
def api_connect():
"""Connect to Zabbix API"""
try:
zapi = ZabbixAPI(server=ZABBIX['url'])
zapi.login(ZABBIX['user'], ZABBIX['pass'])
except Exception,e:
logger.error("Can't login to zabbix server: %s" %(e))
raise ZabbixAlarms, "Can't login to zabbix server: %s" %(e)
开发者ID:knightseal,项目名称:zdash,代码行数:8,代码来源:action.py
示例9: main
def main():
global zapi, hostid
zapi = ZabbixAPI(server=server, path="", log_level=6)
zapi.login(username, password)
hostid = zapi.host.get({"filter":{"host":hostname}})[0]["hostid"]
#print hostid
add_counters(hrl)
开发者ID:BrettHolton,项目名称:MongooseIM,代码行数:10,代码来源:zabbix_add_counters.py
示例10: ICNaaSMonitor
class ICNaaSMonitor(object):
def __init__(self, maas_endpoint):
"""
Initialize the ICNaaS Monitor object
"""
# Connect to MaaS
if maas_endpoint is None:
self.maas_endpoint = '130.92.70.142'
else:
self.maas_endpoint = maas_endpoint
self.server = 'http://' + self.maas_endpoint + '/zabbix'
self.username = MAAS_UID
self.password = MAAS_PWD
self.connFailed = False
# Zabbix API
self.zapi = ZabbixAPI(server=self.server)
for i in range(1,4):
try:
print('*** Connecting to MaaS at ' + self.server)
self.zapi.login(self.username, self.password)
print('*** Connected to MaaS')
self.connFailed = False
break
except Exception as e:
print('*** Caught exception: %s: %s' % (e.__class__, e))
traceback.print_exc()
print('*** Connection to MaaS has failed! Retrying ('+str(i)+').')
self.connFailed = True
time.sleep(3)
if self.connFailed:
print('*** Connection to MaaS has failed! Waiting for an update to try again.')
self.__metrics = []
@property
def metrics(self):
return self.__metrics
@metrics.setter
def metrics(self, value):
self.__metrics = value
pass
def get(self, public_ip):
measured_values = {}
for metric in self.metrics:
measured_values[metric] = self.get_value(metric, public_ip)
if measured_values[metric] is None:
return
return measured_values
def get_value(self, metric, public_ip):
raise NotImplementedError
开发者ID:MobileCloudNetworking,项目名称:icnaas,代码行数:54,代码来源:monitor.py
示例11: delHostZabbix
def delHostZabbix(ip):
# login to zabbix server
zapi = ZabbixAPI(server=ZAB_CONF['server'], path="", log_level=6)
zapi.login(ZAB_CONF['username'], ZAB_CONF['password'])
hostids=zapi.host.get({"output":"extend", 'filter':{'ip':ip}})
if len(hostids) == 1:
return hostids[0]['hostid']
else:
print bold +"\nNothing founded. Please make sure you specified a correct IP \n"+reset
result=zapi.host.delete({"hostid":hostids})
开发者ID:synesis-ru,项目名称:QA-Tools,代码行数:12,代码来源:aws-manage.py
示例12: zabbixHostCreate
def zabbixHostCreate(params):
"""
To create the host in the zabbix server
Args:
{
params - parameter dictionary
}
"""
#Setting the zabbix details
zapi = ZabbixAPI(server = settings.ZABBIX_SERVER)
zapi.login(settings.ZABBIX_USERNAME, settings.ZABBIX_PASSWORD)
returnHost = zapi.host.create(params)
return returnHost
开发者ID:AQORN,项目名称:thunder-engine,代码行数:13,代码来源:common.py
示例13: zabbixHostDelete
def zabbixHostDelete(hostIdList):
"""
To delete the host in the zabbix server
hostIdList - The zabbix host id
"""
try:
zapi = ZabbixAPI(server = settings.ZABBIX_SERVER)
zapi.login(settings.ZABBIX_USERNAME, settings.ZABBIX_PASSWORD)
result = zapi.host.delete(hostIdList)
return True
except Exception, e:
debugException(e)
开发者ID:AQORN,项目名称:thunder-engine,代码行数:13,代码来源:common.py
示例14: DataRetriever
class DataRetriever():
server = "http://127.0.1.1/zabbix"
username = "admin"
password = "zabbix"
hist_type = 3
dens = 1
time_format = "%d-%m-%Y %H:%M:%S"
def __init__(self, item_key):
self.zapi = ZabbixAPI(server=self.server, path="", log_level=3)
self.zapi.login(self.username, self.password)
self.item_key = item_key
def set_config(self, config):
self.hist_type = config.get("general", "hist_type")
self.dens = int(config.get("general", "dens"))
# Time format: "%d-%m-%Y %H:%M:%s"
def get_data(self, str_time_from, str_time_to):
time_from = int(time.mktime(time.strptime(str_time_from, self.time_format)))
time_to = int(time.mktime(time.strptime(str_time_to, self.time_format)))
print str_time_from, time_from
print str_time_to, time_to
hostid = self.zapi.host.get({"output":"extend", "filter": {"host":"localhost"}})[0]["hostid"]
itemid = self.zapi.item.get({"output" : "extend",
"hostids" : [hostid],
"filter" : {"key_" : self.item_key}})[0]['itemid']
H = self.zapi.history.get({"time_from" : str(time_from),
"time_till" : str(time_to),
"output":"extend",
"itemids" : [itemid],
"hostids" : [hostid],
"history" : self.hist_type})
result = [[], []]
i = 0
for el in H:
i += 1
if i % self.dens == 0:
result[0].append(int(el["clock"]) - time_from)
result[1].append(float(el["value"]))
return result
开发者ID:BrettHolton,项目名称:MongooseIM,代码行数:49,代码来源:zabbix_graphs.py
示例15: __init__
def __init__(self, maas_endpoint):
"""
Initialize the RCBaaS Monitor object
"""
# Connect to MaaS
if maas_endpoint is None:
self.maas_endpoint = '160.85.4.27'
else:
self.maas_endpoint = maas_endpoint
self.server = 'http://' + self.maas_endpoint + '/zabbix'
self.username = MAAS_UID
self.password = MAAS_PWD
self.connFailed = False
self.metrics = [RCB_CPU, RCB_LOAD, RCB_TOTAL_MEMORY, RCB_AVAILABLE_MEMORY]
# Zabbix API
self.zapi = ZabbixAPI(server=self.server)
for i in range(1,4):
try:
print('*** Connecting to MaaS')
self.zapi.login(self.username, self.password)
print('*** Connected to MaaS')
self.connFailed = False
except Exception as e:
#print('*** Caught exception: %s: %s' % (e.__class__, e))
#traceback.print_exc()
print('*** Connection to MaaS has failed! Retrying ('+str(i)+').')
self.connFailed = True
time.sleep(3)
if self.connFailed:
print('*** Connection to MaaS has failed! Waiting for an update to try again.')
self.__metrics = []
开发者ID:AleDanish,项目名称:mcn_unibo,代码行数:32,代码来源:monitorRCB.py
示例16: __init__
def __init__(self, region, access_key, secret, pref_if, zbx_url, zbx_user, zbx_pass, set_macro):
self.region = region
self.access_key = access_key
self.secret = secret
self.pref_if = pref_if
self.zbx_url = zbx_url
self.zbx_user = zbx_user
self.zbx_pass = zbx_pass
self.set_macro = set_macro
self.ec2 = boto3.resource(
'ec2',
region_name=region,
aws_access_key_id=access_key,
aws_secret_access_key=secret
)
self.client = boto3.client(
'autoscaling',
region_name=region,
aws_access_key_id=access_key,
aws_secret_access_key=secret
)
self.zapi = ZabbixAPI(server=self.zbx_url)
self.zapi.login(self.zbx_user, self.zbx_pass)
开发者ID:KazumineIgahara,项目名称:zabbix_aws_template,代码行数:25,代码来源:autoscaling_zabbix.py
示例17: __init__
def __init__(self, maas_endpoint):
"""
Initialize the ICNaaS Monitor object
"""
# Connect to MaaS
if maas_endpoint is None:
self.maas_endpoint = '130.92.70.142'
else:
self.maas_endpoint = maas_endpoint
self.server = 'http://' + self.maas_endpoint + '/zabbix'
self.username = MAAS_UID
self.password = MAAS_PWD
self.connFailed = False
# Zabbix API
self.zapi = ZabbixAPI(server=self.server)
for i in range(1,4):
try:
print('*** Connecting to MaaS at ' + self.server)
self.zapi.login(self.username, self.password)
print('*** Connected to MaaS')
self.connFailed = False
break
except Exception as e:
print('*** Caught exception: %s: %s' % (e.__class__, e))
traceback.print_exc()
print('*** Connection to MaaS has failed! Retrying ('+str(i)+').')
self.connFailed = True
time.sleep(3)
if self.connFailed:
print('*** Connection to MaaS has failed! Waiting for an update to try again.')
self.__metrics = []
开发者ID:MobileCloudNetworking,项目名称:icnaas,代码行数:32,代码来源:monitor.py
示例18: ImportCommand
class ImportCommand(Command):
description = "import zabbix global scripts and global macros"
user_options = [("frontend-url=", "f", "zabbix frontend url"),
("user=", "u", "zabbix user name"),
("password=", "p", "zabbix password")]
def initialize_options(self):
# set default value
self.frontend_url = "http://localhost/zabbix"
self.user = "Admin"
self.password = "zabbix"
def finalize_options(self):
pass
def run(self):
from zabbix_api import ZabbixAPI, ZabbixAPIException
from xml.etree import ElementTree
# connect zabbix frontend
try:
self.zabbix_api = ZabbixAPI(self.frontend_url)
self.zabbix_api.login(self.user, self.password)
except ZabbixAPIException, e:
print "Failed to connect zabbix frontend: %s" % str(e[0]).partition("while sending")[0]
return
# import templates
print "Import templates"
try:
with open(os.path.join(pwd, "misc/import_data/templates.xml")) as f:
template_xml = f.read()
req = self.zabbix_api.json_obj("configuration.import", {
"format": "xml",
"source": template_xml,
"rules": {
"items": {"createMissing": True},
"applications": {"createMissing": True},
"graphs": {"createMissing": True},
"groups": {"createMissing": True},
"templateLinkage": {"createMissing": True},
"templates": {"createMissing": True},
"triggers": {"createMissing": True},
}
})
self.zabbix_api.do_request(req)
except IOError, e:
print " " + str(e)
开发者ID:tech-sketch,项目名称:hyclops,代码行数:46,代码来源:setup.py
示例19: main
def main():
zapi = ZabbixAPI(server='http://zabbix-server01.dc.nova/zabbix')
zapi.login(zabbix_user, zabbix_pwd)
host_response = zapi.host.get({'groupids': [8,9],
'selectInterfaces': 'extend'})
hosts = []
for host in host_response:
hosts.append({'nome': host['host'],
'ip': host['interfaces'][0]['ip'],
'host_id': int(host['hostid'])})
arquivo = os.path.dirname(os.path.realpath(__file__)) + '/servidores_zabbix.json'
with open(arquivo, 'w') as arq:
json.dump(hosts, arq)
开发者ID:dlopes7,项目名称:zabbix_admin,代码行数:17,代码来源:get_zabbix_machines.py
示例20: zbxLogin
def zbxLogin(self):
self.zapi = ZabbixAPI(server=self.server, log_level=0)
try:
self.zapi.login(self.username, self.password)
print "Zabbix API Version: %s" % self.zapi.api_version()
print "Logged in: %s" % str(self.zapi.test_login())
except ZabbixAPIException, e:
sys.stderr.write(str(e) + "\n")
开发者ID:spscream,项目名称:Zabbix-utils,代码行数:8,代码来源:zabbix_utils.py
注:本文中的zabbix_api.ZabbixAPI类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论