-
Notifications
You must be signed in to change notification settings - Fork 10
/
zabdig
executable file
·890 lines (759 loc) · 30.4 KB
/
zabdig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
#!/usr/bin/env python3
# zabdig (part of ossobv/vcutil) // wdoekes/2017-2023 // Public Domain
#
# Quickly query the zabbix server for hosts and hostnames/IPs, using the
# Zabbix JSON API.
#
# Usage examples:
#
# $ zabdig walter
# Walter Privé wjdsys.example.com (zabbix-proxy2)
# walter.internal.lan 10.32.1.5 (zabbix-proxy-lan)
# walterdev.example.com walterdev.example.com
#
# $ zabdig walter.internal.lan
# 10.32.1.5
#
# Configure by setting up a ~/.zabbixrc with sections:
#
# [myorganisation]
# api=https://zabbix-server.example.com/api_jsonrpc.php
# user=myusername
# password=mypassword
#
# (If you leave out user/password it will try to get it from your Secret
# Storage API (keyring).)
#
# If you have multiple zabbix servers you wish to speak to, add
# additional sections. Use zabdig -g SECTION to select a different
# section/organisation than the first.
#
# If you have zabbix-proxies that identify as 127.0.0.1, you can add a
# DNS name (while keeping use-IP), and the DNS will be shown instead.
#
# See zabdig --help for more info.
#
# Tip /usr/local/bin/zssh:
#
# #!/bin/sh
# host="$1"; shift
#
# ip=$(zabdig "$host")
# if ! echo "$ip" | grep -qE '^([0-9]+[.]){3}[0-9]+$'; then
# echo "Bad IP: $ip" >&2
# exit 1
# fi
#
# # Add -lSOMEUSER at tail, unless there is a "-l" somewhere already.
# add_min_l_arg=-lSOMEUSER # optional..
# for arg in "$@"; do
# test "${arg#-l}" != "$arg" && add_min_l_arg= && break
# done
#
# echo "(connecting to $ip ...)" >&2
# # (move $add_min_l_arg to the left of "$@" on ssh before version 8)
# exec ssh "$ip" "$@" $add_min_l_arg
#
# Requirements: requests (python3-requests)
#
import argparse
import configparser
import json
import os
import requests
import sys
import time
from datetime import datetime, timezone
from fnmatch import fnmatch
from warnings import warn
class ZConfigError(ValueError):
pass
class ZInterfaceError(IOError):
pass
class ZLoginError(ZInterfaceError):
pass
class ZDataError(ZInterfaceError):
pass
class Needle(object):
"Needle is used for hostname searches"
def __init__(self, glob_pattern):
self._exact_glob_pattern = glob_pattern
self._contains_glob_pattern = '*{}*'.format(glob_pattern)
def as_string(self):
"Return the longest part that can be used in a 'contains' search"
# So if pve?.dr.osso.cloud is passed, we'll split it into longer
# matches and pre-search on the longest part: return ".dr.osso.cloud"
static_parts = self._exact_glob_pattern.replace('?', '*').split('*')
static_parts.sort(key=(lambda x: (-len(x), x)))
return static_parts[0] # longest non-magic part
def is_exactly(self, string):
"Return True if needle matches string exactly"
return fnmatch(string, self._exact_glob_pattern)
def is_found_in(self, string):
"Return True if needle is found somewhere in string"
return fnmatch(string, self._contains_glob_pattern)
class ZAlert(object):
SEVERITIES = {
0: 'N/A', # Unclassified
1: 'INFO', # Info
2: 'WARN', # Warning
3: 'AVG', # Average
4: 'HIGH', # High
5: 'CRIT', # Disaster
}
@staticmethod
def severity_mask_to_zabbix(mask):
"""
We've defined severity starting with 1 for disaster as a bitmask.
mask: 1=disaster, 2=high, 4=avg..
zabbix: 0=unclass, 1=info, 2=warn, 3=avg, 4=high, 5=disaster
"""
if mask == 0:
mask = 63 # ALL
ret = []
if mask & 1:
ret.append(5) # Disaster
if mask & 2:
ret.append(4) # High
if mask & 4:
ret.append(3) # Average
if mask & 8:
ret.append(2) # Warning
if mask & 16:
ret.append(1) # Info
if mask & 32:
ret.append(0) # Unclassified
return ret
@classmethod
def severity_zabbix_to_str(cls, num):
return cls.SEVERITIES[num]
def __init__(self, problem, trigger):
assert trigger['value'] == '1', trigger # 1=Problem
assert trigger['flags'] in (
'0', # Normal item
'1', # Discovery rule
'2', # Item prototype
'4', # Auto-created item
), trigger # XXX?
assert len(trigger['hosts']) == 1, trigger
host = trigger['hosts'][0]
del trigger['hosts']
assert all(
i['hostid'] == host['hostid'] for i in trigger['items']), (
trigger)
items = trigger['items']
del trigger['items']
self._problem = problem
self._trigger = trigger
self._host = host
self._items = items
@property
def description(self):
if not hasattr(self, '_description'):
if self._trigger['error']:
self._description = '{} [{}]'.format(
self._problem['name'], self._trigger['error'])
else:
self._description = self._problem['name']
self._description = (
self._description.replace('\n', ' ').replace('\r', ''))
return self._description
@property
def hostname(self):
return self._host['host']
@property
def host_enabled(self):
assert self._host['status'] in ('0', '1')
return self._host['status'] != '1' # 1=disabled
@property
def all_items_enabled(self):
assert all(i['status'] in ('0', '1') for i in self._items), (
self._items)
return all(i['status'] != '1' for i in self._items) # 1=disabled
@property
def enabled(self):
assert self._problem['suppressed'] in ('0', '1'), self._problem
assert self._trigger['status'] in ('0', '1'), self._trigger
if self._problem['suppressed'] == '1':
warn('trigger suppressed on {0.hostname}: {0.description}'.format(
self))
return False
return self._trigger['status'] != '1' # 1=disabled
@property
def begin(self):
if not hasattr(self, '_begin'):
ts = int(self._problem['clock']) + (
int(self._problem['ns']) / 1000000000.0)
tz = timezone.utc if False else None # FIXME?
self._begin = datetime.fromtimestamp(ts, tz=tz)
return self._begin
@property
def severity(self):
num = int(self._problem['severity'])
return self.severity_zabbix_to_str(num)
def __str__(self):
return repr(self)
def __repr__(self):
begin = self.begin.strftime('%Y-%m-%dT%H:%M:%S')
return (
'alert:{0.severity:4s} {1}: {0.description} '
'({0.hostname})'.format(self, begin))
class ZHistoricAlert(ZAlert):
def __init__(self, problem, trigger):
hacked_trigger_value, trigger['value'] = trigger['value'], '1'
super().__init__(problem, trigger)
trigger['value'] = hacked_trigger_value
resolved = problem['relatedObject']
del problem['relatedObject']
assert resolved['triggerid'] == trigger['triggerid'], (
problem, trigger, resolved)
self._end_timestamp = resolved['lastchange']
self._end_value = resolved['value']
# self._opdatas = (problem['opdata'], resolved['opdata'])
@property
def end(self):
if not hasattr(self, '_end'):
assert self._problem['value'] == '1'
if self._end_value == '1':
self._end = None
else:
ts = int(self._end_timestamp)
tz = timezone.utc if False else None # FIXME?
self._end = datetime.fromtimestamp(ts, tz=tz)
return self._end
def __repr__(self):
begin = self.begin.strftime('%Y-%m-%dT%H:%M:%S')
if self.end:
end = self.end.strftime('%Y-%m-%dT%H:%M:%S')
offset = (self.end - self.begin)
offset = '({0:6.2f}h)'.format(offset.total_seconds() / 3600.0)
else:
end = '--..-..-..T..:..:..'
offset = '( -.--h)'
return (
'alert:{0.severity:4s} {1}..{2} {3}: {0.description} '
'({0.hostname})'.format(self, begin, end, offset))
class ZBaseHost(object):
@classmethod
def matches_needle(cls, hostinfo, needle):
return needle.matches(hostinfo['name'])
def __init__(self, hostinfo):
self._hostinfo = hostinfo
try:
self.name = hostinfo['name']
except KeyError:
assert 'proxy_address' in hostinfo, hostinfo
self.name = hostinfo['host'] # proxies do not have a name
def get_name(self):
return (
self.name or # "visible name"
self._hostinfo['host'] or
'<ZHost({})>'.format(self._hostinfo['hostid']))
def __str__(self):
return self.get_name()
class ZHost(ZBaseHost):
def __init__(self, hostinfo, proxies):
super(ZHost, self).__init__(hostinfo)
if proxies and hostinfo['proxy_hostid'] != '0':
self.proxy = proxies[hostinfo['proxy_hostid']]
else:
self.proxy = None
def has_ip(self, ip):
return (ip in self.get_zabbix_addr_list())
def get_zabbix_addr_first(self):
addr_list = self.get_zabbix_addr_list()
if not addr_list:
addr_list = ['NONE']
return addr_list[0]
def get_zabbix_addr(self):
return ', '.join(self.get_zabbix_addr_list())
def get_zabbix_addr_list(self):
if not hasattr(self, '_zabbix_addr_list'):
exit_ip4 = self.get_exit_ip4()
ret = []
for interface in self._hostinfo['interfaces']:
# type 1 = Zabbix Agent
# type 2 = SNMP
# type 3 = IPMI
# type 4 = JMX
if int(interface['type']) == 1:
if int(interface['useip']):
# For zabbix proxies, we see the lo IP only.. super
# annoying when trying to find where it is. Hope
# that someone (ab)used the DNS field for more info.
if interface['ip'] == '127.0.0.1':
if interface['dns']:
ret.append(interface['dns'])
elif exit_ip4:
ret.append(exit_ip4)
else:
# 127.0.0.1 anyway..
ret.append(interface['ip'])
else:
ret.append(interface['ip'])
else:
ret.append(interface['dns'])
self._zabbix_addr_list = list(sorted(set(ret)))
# Always add exit_ip4; but add it last, as we may not be
# able to access anything through it directly.
if exit_ip4 and exit_ip4 not in self._zabbix_addr_list:
self._zabbix_addr_list.append(exit_ip4)
return self._zabbix_addr_list
def get_exit_ip4(self):
if self._hostinfo.get('inventory') == []:
print('WARNING: {name} does not have Inventory enabled'.format(
name=self.get_name()), file=sys.stderr)
return None
return self._hostinfo.get('inventory', {}).get('host_router', None)
def is_available(self):
if not hasattr(self, '_is_available'):
availables = [
iface.get('available')
for iface in self._hostinfo['interfaces']]
if availables:
# Available not set on the interfaces? Then this is
# zabbix-server<6.0
if all(available is None for available in availables):
availables = [self._hostinfo.get('available')]
availables.sort(reverse=True)
available = availables[0] # '2', '1', '0', None
else:
available = '0' # no interfaces, no state
# zabbix-server>=6.0 has active check polling. if the proxies
# haven't sent any active updates, then the state is "unseen"
if available == '0':
if self.get_zabbix_addr() in ('127.0.0.1', ''):
pass
else:
warn(
'one or more hosts have unknown state; '
'if you have zabbix-proxy<6.0 this is expected')
available = '1' # make it 1=up
assert available in ('0', '1', '2'), self._hostinfo
self._is_available = available
if self._is_available == '0': # 0=unseen
return None
return (self._is_available == '1') # 1=up, 2=down
def is_enabled(self):
assert self._hostinfo.get('status') in ('0', '1'), self._hostinfo
return self._hostinfo.get('status') == '0' # 1 is Disabled
def __str__(self):
if not self.is_enabled():
return '{}--OFF'.format(self.get_name())
elif self.is_available() is None:
return '{}--UNKNOWN'.format(self.get_name())
elif self.is_available() is False:
return '{}--DOWN'.format(self.get_name())
return self.get_name()
def __eq__(self, other):
return self._hostinfo['hostid'] == other._hostinfo['hostid']
def __lt__(self, other):
if self.name != other.name:
return self.name < other.name
return self._hostinfo['hostid'] < other._hostinfo['hostid']
class ZInterface(object):
def __init__(self, url, username, password):
if not url or not username or not password:
raise ZConfigError(
'cannot login without api/url, username and password')
self.url = url
self.username = username
self.password = password
self.token = None
self.postid = 0
def _zabbix_call(self, method, params):
self.postid += 1
data = {
'jsonrpc': '2.0',
'method': method,
'params': params,
'id': self.postid,
}
data['auth'] = self.token # can be 'null'
return self._zabbix_post(self.url, data)
def _zabbix_post(self, url, data):
res = requests.post(
url, data=json.dumps(data),
headers={'Content-Type': 'application/json-rpc'})
try:
js = res.json()
except ValueError as e:
raise ZInterfaceError(
'JSON error "{}" in\n\n {!r}...\n\n'.format(
e, res.content[0:512]), data)
if 'error' in js:
raise ZInterfaceError(js['error'], data)
return js['result']
def _login(self):
if not self.token:
class PrivacyDict(dict):
"Don't show username/password in stack traces."
def __repr__(self):
# Yes, this repr is broken for abnormal keys, but
# we don't use those.
return '{{{}}}'.format(', '.join(
"'{}': '****'".format(key)
for key in sorted(self.keys())))
try:
self.token = self._zabbix_call(
'user.login',
PrivacyDict(
username=self.username, # user->username since 6.0+
password=self.password))
except ZInterfaceError as e:
if e.args[0] == {
'code': -32602, 'message': 'Invalid params.',
'data': (
'Invalid parameter "/": unexpected parameter '
'"username".')}:
try:
self.token = self._zabbix_call(
'user.login',
PrivacyDict(
user=self.username,
password=self.password))
except ZInterfaceError as e2:
raise ZLoginError(*e.args) from e2
else:
raise ZLoginError(*e.args) from e
def get_alerts(self, severity, enabled_only=True):
self._login()
problems = self._zabbix_call(
'problem.get',
{'output': [
'eventid', 'r_eventid', 'objectid', 'clock', 'ns', 'severity',
'suppressed', 'name'],
'source': 0, # 0=trigger
'object': 0, # 0=trigger
# 'groupids': [...],
# 'hostids': [10884],
'recent': False, # only UNRESOLVED
'severities': ZAlert.severity_mask_to_zabbix(severity)})
triggerids = list(set([i['objectid'] for i in problems]))
triggers_by_triggerid = dict(
(i['triggerid'], i) for i in self._zabbix_call(
'trigger.get',
{'output': [
'triggerid', 'status', 'error', 'suppressed',
'flags', 'value'],
'selectHosts': ['hostid', 'host', 'status'],
'selectItems': ['hostid', 'status'],
'triggerids': triggerids}))
alerts = []
for problem in problems:
trigger = triggers_by_triggerid.get(problem['objectid'])
if not trigger:
# This may auto-heal if the trigger was recently removed.
# Otherwise:
# delete ev from events ev
# left join triggers tr on tr.triggerid = ev.objectid
# where tr.triggerid is null and
# ev.source = 0 and ev.object = 0;
warn('no trigger for alert {!r}'.format(problem))
continue
alert = ZAlert(problem, trigger)
if not alert.host_enabled:
# host is disabled, skip
continue
if not alert.all_items_enabled:
# Some of the trigger items are disabled. This is generally
# rather annoying. Do check and re-enable them if possible.
# There are better ways to fix this.
warn('some or all items disabled in {}'.format(alert))
continue
if alert.enabled or not enabled_only:
alerts.append(alert)
alerts.sort(key=(lambda x: (
x._problem['severity'], x.description, x.hostname)))
if False:
import pprint
for alert in alerts:
print(alert)
pprint.pprint(alert._problem)
pprint.pprint(alert._trigger)
pprint.pprint(alert._host)
pprint.pprint(alert._items)
return alerts
def get_alert_history(self, severity):
self._login()
# Search between -1d and now.
now = int(time.time())
then = now - 86400
# value 0=OK, 1=problem
# We need the RelatedObject to get the event-close state.
problems = self._zabbix_call(
'event.get',
{'output': [
'acknowledged', 'r_eventid', 'eventid', 'clock', 'ns',
'objectid', 'value', 'severity', 'suppressed', 'name',
# 'opdata',
],
'source': 0, # 0=trigger
'object': 0, # 0=trigger
# 'groupids': [...],
# 'hostids': [11343],
# 'acknowledged': True, # only ACKed
'suppressed': False, # normal state events only
'selectRelatedObject': [
'triggerid', 'lastchange', 'value',
# 'opdata'
],
# This may not be very efficient. We could look into
# fetching the hosts manually...
'selectHosts': ['hostid', 'host', 'status'],
'problem_time_from': then,
'problem_time_till': now,
'severities': ZAlert.severity_mask_to_zabbix(severity)})
# Prune the list of problems. Keep only if:
# - if there is a relatedObject, or
# - the start time is fresh enough
problems = [
i for i in problems
if i['relatedObject'] or int(i['clock']) > then]
triggerids = list(set([i['objectid'] for i in problems]))
triggers_by_triggerid = dict(
(i['triggerid'], i) for i in self._zabbix_call(
'trigger.get',
{'output': [
'triggerid', 'status', 'error', 'suppressed',
'flags', 'value'],
'selectHosts': ['hostid', 'host', 'status'],
'selectItems': ['hostid', 'status'],
'triggerids': triggerids}))
alerts = []
for problem in problems:
trigger = triggers_by_triggerid.get(problem['objectid'])
if not trigger:
warn('no trigger for alert {!r}'.format(problem))
continue
# Copy trigger dict so the ZHistoricAlert gets to own/mutate it.
trigger_copy = dict(trigger)
alert = ZHistoricAlert(problem, trigger_copy)
if not alert.host_enabled:
# host is disabled, skip
continue
assert alert.all_items_enabled, alert
alerts.append(alert)
alerts.sort(key=(lambda x: (
x.begin, x._problem['severity'], x.description, x.hostname)))
return alerts
def get_hosts(self, hostname_needle):
self._login()
params = {
'output': [
'name', 'host', 'interfaces', 'proxy_hostid',
'status', 'available'],
# 'output': ['name', 'interfaces', 'groups', 'proxy_hostid',
# 'status'],
'selectInventory': ['host_router'], # or 'extend' for _all_
'selectInterfaces': 'extend',
'selectGroups': 'extend',
}
if hostname_needle:
params['search'] = {'name': hostname_needle.as_string()}
hosts = self._zabbix_call('host.get', params)
for host in hosts:
try:
if (not hostname_needle or
hostname_needle.is_found_in(host['name'])):
yield ZHost(host, self.get_proxies())
except ZInterfaceError:
raise
except Exception as e:
raise ZDataError('got err {!r} for hostinfo {}'.format(
e, host))
def get_proxies(self):
if not hasattr(self, '_get_proxies'):
self._login()
# zabbix-server >= 6.0 does not have a proxy.name anymore. Use the
# host instead.
proxies = self._zabbix_call(
'proxy.get',
{'output': ['host', 'proxy_address', 'proxyid']})
try:
self._get_proxies = dict(
(proxy['proxyid'], ZBaseHost(proxy))
for proxy in proxies)
except ZInterfaceError:
raise
except Exception as e:
raise ZDataError('got err {!r} for proxies {}'.format(
e, proxies))
return self._get_proxies
class LocalConfig(object):
def __init__(self):
self.config = configparser.ConfigParser()
self.config.read(os.path.expanduser('~/.zabbixrc')) # silent failure
if self.config.sections():
self.section = self.config.sections()[0]
else:
self.section = None
def select_section(self, section):
if section in self.config.sections():
self.section = section
else:
raise ZConfigError('no such section in config')
def get(self, key):
if not self.section:
return None
return self.config[self.section].get(key, None)
def get_from_secret_storage(section):
"Requires python3-secretstorage for Freedesktop Secret Service API"
import secretstorage
from base64 import b64decode, b64encode
from contextlib import closing
with closing(secretstorage.dbus_init()) as conn:
coll = secretstorage.get_default_collection(conn)
if coll.is_locked():
coll.unlock()
# FIXME: section? or DEFAULT?
attrs = {'application': 'zabdig'}
if section:
attrs['section'] = section
res = [i for i in coll.search_items(attrs)]
# FIXME: add 'or True' to overwrite previous passwords
if not res: # or True:
import getpass
print('No password stored; add one?', attrs)
print('username: ', end='')
username = input().strip()
password = getpass.getpass('password: ')
user_pass = b64encode(
'{}:{}'.format(username, password).encode('utf-8'))
# FIXME: we should check auth first before storing..
# FIXME: we should ask for a new password if we get one of:
# fetch failed: [{'code': -32602, 'message': 'Invalid params.',
# 'data': 'Incorrect user name or password or account is \
# temporarily blocked.'}]
# fetch failed: [{'code': -32500, 'message': 'Application error.',
# 'data': 'Incorrect user name or password or account is \
# temporarily blocked.'}]
coll.create_item(
'zabdig user/pass', attributes=attrs,
replace=True, secret=user_pass)
res = [i for i in coll.search_items(attrs)]
assert len(res) == 1, res
try:
res[0].ensure_not_locked()
except secretstorage.exceptions.LockedException:
dialog_dismissed = res[0].unlock() # request user unlock
if dialog_dismissed:
raise
user_pass = res[0].get_secret()
user, password = b64decode(user_pass).decode('utf-8').split(':', 1)
return (user, password)
def show_host(host):
print('[{}]'.format(host.get_name()))
print('Status = {}{}'.format(
'ON' if host.is_available() else 'OFF',
'' if host.is_enabled() else ' (DISABLED)'))
print('Address = {}'.format(host.get_zabbix_addr()))
print('ExternalIP4 = {}'.format(host.get_exit_ip4()))
print('Proxy = {}'.format(host.proxy or ''))
print()
if __name__ == '__main__':
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'-g', '--section', dest='section', help=(
'Use SECTION from ~/.zabbixrc for defaults'))
parser.add_argument(
'-A', '--api', dest='api', help=(
'Zabbix json_rpc API URL, for example: '
'https://zabbix.example.nl/api_jsonrpc.php'))
parser.add_argument(
'-u', '--user', dest='user', help=(
'API username'))
parser.add_argument(
'-p', '--password', dest='password', help=(
'API password'))
parser.add_argument(
'-a', '--all', action='store_true', help=(
'List all hosts even if there are exact matches'))
parser.add_argument(
'-S', '--alert-severity', action='store', default=3, type=int,
help=(
'Show info about current alerts, use bitmask: 0=all, '
'1=disaster, 2=high, 4=avg, 8=warn, 16=info, 32=unclass'))
parser.add_argument(
'--show', choices=('host', 'alerts', 'ahist'), help=(
'Show info about host, alerts, alert history'))
parser.add_argument(
'-x', '--with-ip', help=(
'Filter by IP-address')) # compare 'dig -x'
parser.add_argument(
'search', nargs='?', type=Needle, help=(
'Hostname to search for (* and ? are allowed)'))
args = parser.parse_args()
lconf = LocalConfig()
if args.section:
try:
lconf.select_section(args.section)
except ZConfigError:
print('no such section found in config file', file=sys.stderr)
sys.exit(1)
else:
args.section = lconf.section
api = args.api or lconf.get('api')
user = args.user or lconf.get('user')
password = args.password or lconf.get('password')
# Ooh.. quick hacks!
if not user or not password:
(user, password) = get_from_secret_storage(args.section)
try:
zint = ZInterface(api, user, password)
except ZConfigError as e:
print(
'login failed: {}; see zabdig --help'.format(e),
file=sys.stderr)
sys.exit(1)
if args.show in ('alerts', 'ahist'):
if args.search:
raise NotImplementedError() # not yet
alerts = {
'alerts': zint.get_alerts,
'ahist': zint.get_alert_history,
}[args.show](args.alert_severity)
for alert in alerts:
print(alert)
print(len(alerts))
exit(0)
try:
hosts = list(zint.get_hosts(args.search))
except ZInterfaceError as e:
print('fetch failed: {}'.format(e), file=sys.stderr)
sys.exit(1)
if not hosts:
print('nothing found', file=sys.stderr)
sys.exit(1)
# Limit hosts by IP address.
# FIXME: perhaps do server-side search if possible here?
if args.with_ip:
hosts = [host for host in hosts if host.has_ip(args.with_ip)]
# Unless the user supplied --all, if there is a single match, use that.
exact_match = False
if args.search and not args.all and not args.with_ip:
exact_hosts = [
host for host in hosts if args.search.is_exactly(host.name)]
if len(exact_hosts) == 1:
exact_match = True
hosts = exact_hosts
# One match, show the IP.
if not args.show and exact_match:
print(hosts[0].get_zabbix_addr_first())
sys.exit(0)
for host in sorted(hosts):
if args.show == 'host':
show_host(host)
elif args.show == 'alerts':
raise NotImplementedError() # handled earlier
elif args.show:
raise NotImplementedError() # unexpected?
else:
print('{name!s:30} {addr!s}{optional_proxy!s}'.format(
name=host,
addr=host.get_zabbix_addr(),
optional_proxy=(
host.proxy and ' ({!s})'.format(host.proxy) or '')))
main()
# vim: set ts=8 sw=4 sts=4 et ai: