/
cli.py
6867 lines (5237 loc) · 227 KB
/
cli.py
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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Authors:
# rafael@e-mc2.net / https://e-mc2.net/
#
# Copyright (c) 2014-2017 USIT-University of Oslo
#
# This file is part of Zabbix-CLI
# https://github.com/usit-gd/zabbix-cli
#
# Zabbix-CLI is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Zabbix-CLI is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zabbix-CLI. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import print_function
import cmd
import datetime
import distutils.version
import glob
import hashlib
import json
import logging
import os
import random
import re
import shlex
import signal
import subprocess
import sys
import textwrap
import time
# ipaddress is a dependency in python2 and stdlib in python3
import ipaddress # noqa: I100, I202
import zabbix_cli
import zabbix_cli.apiutils
import zabbix_cli.utils
from zabbix_cli.prettytable import ALL, FRAME, PrettyTable
from zabbix_cli.pyzabbix import ZabbixAPI
# Python 2, 3 support
try:
input = raw_input
except NameError:
pass
logger = logging.getLogger(__name__)
class zabbixcli(cmd.Cmd):
'''
This class implements the Zabbix shell. It is based on the python module cmd
'''
# ###############################
# Constructor
# ###############################
def __init__(self, conf, username='', password='', auth_token=''):
cmd.Cmd.__init__(self)
self.version = self.get_version()
self.conf = conf
self.api_username = username
self.api_password = password
self.api_auth_token = auth_token
self.output_format = 'table'
self.use_colors = self.conf.use_colors
self.use_auth_token_file = self.conf.use_auth_token_file
self.use_paging = self.conf.use_paging
self.bulk_execution = False
self.non_interactive = False
self.system_id = self.conf.system_id
self.prompt = '[zabbix-cli ' + self.api_username + '@' + self.system_id + ']$ '
logger.debug('Zabbix API url: %s', self.conf.zabbix_api_url)
try:
self.zapi = ZabbixAPI(self.conf.zabbix_api_url)
if self.conf.cert_verify.upper() == "ON":
self.zapi.session.verify = True
elif self.conf.cert_verify.upper() == "OFF":
self.zapi.session.verify = False
else:
self.zapi.session.verify = self.conf.cert_verify
zabbix_auth_token_file = os.getenv('HOME') + '/.zabbix-cli_auth_token'
self.api_auth_token = self.zapi.login(self.api_username, self.api_password, self.api_auth_token)
self.zapi.user.get(userids=-1) # Dummy call to verify authentication
except Exception as e:
print('\n[ERROR]: ' + str(e) + '\n')
logger.error('Problems logging on to %r', self.conf.zabbix_api_url)
zabbix_auth_token_file = os.getenv('HOME') + '/.zabbix-cli_auth_token'
if os.path.isfile(zabbix_auth_token_file):
try:
os.remove(zabbix_auth_token_file)
logger.info('API-auth-token has probably expired. File %s deleted.', zabbix_auth_token_file)
except Exception as e:
print('\n[ERROR]: ' + str(e) + '\n')
logger.error('Problems deleting file %s - %s', zabbix_auth_token_file, e)
sys.exit(1)
sys.exit(1)
logger.debug('Connected to Zabbix JSON-API')
self.api_version = self.zapi.apiinfo.version()
#
# The file $HOME/.zabbix-cli_auth_token is created if it does not exists.
#
# Format:
# USERNAME::API-auth-token returned after the las login.
#
if self.use_auth_token_file == 'ON' and not os.path.isfile(zabbix_auth_token_file):
with open(zabbix_auth_token_file, 'w') as auth_token_file:
auth_token_file.write(self.api_username + '::' + self.api_auth_token)
auth_token_file.flush()
logger.info('API-auth-token file created.')
self.intro = '\n#############################################################\n' + \
'Welcome to the Zabbix command-line interface (v' + self.version + ')\n' + \
'Connected to server ' + self.conf.zabbix_api_url + ' (v' + self.api_version + ')\n' + \
'#############################################################\n' + \
'Type help or \\? to list commands.\n'
#
# Populate the dictionary used as a cache with hostid and
# hostname data
#
self.hostid_cache = self.populate_hostid_cache()
#
# Populate the dictionary used as a cache with proxyid and
# proxy name data
#
self.proxyid_cache = self.populate_proxyid_cache()
#
# Populate the dictionary used as a cache with hostgroupname and
# hostgroupid
#
self.hostgroupname_cache = self.populate_hostgroupname_cache()
def do_show_maintenance_definitions(self, args):
'''
DESCRIPTION:
This command shows maintenance definitions global
information. The logical operator AND will be used if one
defines more than one parameter.
COMMAND:
show_maintenance_definitions [definitionID]
[hostgroup]
[host]
[definitionID]
--------------
Definition ID. One can define more than one value.
[hostgroup]:
------------
Hostgroup name. One can define more than one value.
[host]:
-------
Hostname. One can define more than one value.
'''
result_columns = {}
result_columns_key = 0
try:
arg_list = shlex.split(args)
except ValueError as e:
print('\n[ERROR]: ' + str(e) + '\n')
return False
#
# Command without parameters
#
if len(arg_list) == 0:
try:
print('--------------------------------------------------------')
maintenances = input('# MaintenanceID [*]: ').strip()
hostgroups = input('# Hostgroups [*]: ').strip()
hostnames = input('# Hosts [*]: ').strip()
print('--------------------------------------------------------')
except EOFError:
print('\n--------------------------------------------------------')
print('\n[Aborted] Command interrupted by the user.\n')
return False
#
# Command with parameters
#
elif len(arg_list) == 3:
maintenances = arg_list[0].strip()
hostgroups = arg_list[1].strip()
hostnames = arg_list[2].strip()
#
# Command with the wrong number of parameters
#
else:
self.generate_feedback('Error', ' Wrong number of parameters used.\n Type help or \\? to list commands')
return False
#
# Generate maintenances, hosts and hostgroups IDs
#
try:
maintenance_list = []
hostnames_list = []
hostgroups_list = []
if maintenances == '*':
maintenances = ''
if hostgroups == '*':
hostgroups = ''
if hostnames == '*':
hostnames = ''
if maintenances != '':
for maintenance in maintenances.split(','):
maintenance_list.append(str(maintenance).strip())
if hostgroups != '':
for hostgroup in hostgroups.split(','):
if hostgroup.isdigit():
hostgroups_list.append(str(hostgroup).strip())
else:
hostgroups_list.append(str(self.get_hostgroup_id(hostgroup.strip())))
if hostnames != '':
for hostname in hostnames.split(','):
if hostname.isdigit():
hostnames_list.append(str(hostname).strip())
else:
hostnames_list.append(str(self.get_host_id(hostname.strip())))
except Exception as e:
logger.error('Problems getting maintenance definitions information - %s', e)
self.generate_feedback('Error', 'Problems getting maintenance definitions information')
return False
query = {
"output": "extend",
"selectGroups": ["name"],
"selectHosts": ["name"],
"sortfield": "maintenanceid",
"sortorder": "ASC",
"searchByAny": True
}
if maintenance_list:
query["maintenanceids"] = maintenance_list
if hostgroups_list:
query["groupids"] = hostgroups_list
if hostnames_list:
query["hostids"] = hostnames_list
#
# Get result from Zabbix API
#
try:
result = self.zapi.maintenance.get(**query)
logger.info('Command show_maintenance_definitions executed')
except Exception as e:
logger.error('Problems getting maintenance definitions information - %s', e)
self.generate_feedback('Error', 'Problems getting maintenance definitions information')
return False
#
# Get the columns we want to show from result
#
for maintenance in result:
if (int(time.time()) - int(maintenance['active_till'])) > 0:
state = 'Expired'
else:
state = 'Active'
if self.output_format == 'json':
result_columns[result_columns_key] = {'maintenanceid': maintenance['maintenanceid'],
'name': maintenance['name'],
'maintenance_type': zabbix_cli.utils.get_maintenance_type(int(maintenance['maintenance_type'])),
'state': state,
'active_till': maintenance['active_till'],
'hosts': maintenance['hosts'],
'groups': maintenance['groups'],
'description': maintenance['description']}
else:
host_list = []
for host in maintenance['hosts']:
host_list.append(host['name'])
host_list.sort()
group_list = []
for group in maintenance['groups']:
group_list.append(group['name'])
group_list.sort()
result_columns[result_columns_key] = {'1': maintenance['maintenanceid'],
'2': '\n'.join(textwrap.wrap(maintenance['name'], 30)),
'3': zabbix_cli.utils.get_maintenance_type(int(maintenance['maintenance_type'])),
'4': state,
'5': datetime.datetime.utcfromtimestamp(float(maintenance['active_till'])).strftime('%Y-%m-%dT%H:%M:%SZ'),
'6': '\n'.join(host_list),
'7': '\n'.join(group_list),
'8': '\n'.join(textwrap.wrap(maintenance['description'], 40))}
result_columns_key = result_columns_key + 1
#
# Generate output
#
self.generate_output(result_columns,
['ID', 'Name', 'Type', 'State', 'To', 'Hostnames', 'Hostgroups', 'Description'],
['Name', 'Description', 'Hostnames', 'Hostgroups'],
['ID'],
ALL)
def do_show_maintenance_periods(self, args):
'''
DESCRIPTION:
This command shows maintenance periods global information.
COMMAND: show_maintenance_periods [definitionID]
[definitionID]
--------------
Definition ID. One can define more than one value.
'''
result_columns = {}
result_columns_key = 0
try:
arg_list = shlex.split(args)
except ValueError as e:
print('\n[ERROR]: ' + str(e) + '\n')
return False
#
# Command without parameters
#
if len(arg_list) == 0:
try:
print('--------------------------------------------------------')
maintenances = input('# MaintenanceID [*]: ').strip()
print('--------------------------------------------------------')
except EOFError:
print('\n--------------------------------------------------------')
print('\n[Aborted] Command interrupted by the user.\n')
return False
#
# Command with parameters
#
elif len(arg_list) == 1:
maintenances = arg_list[0].strip()
#
# Command with the wrong number of parameters
#
else:
self.generate_feedback('Error', ' Wrong number of parameters used.\n Type help or \\? to list commands')
return False
#
# Generate maintenances, hosts and hostgroups IDs
#
maintenance_list = []
if maintenances == '*':
maintenances = ''
if maintenances != '':
for maintenance in maintenances.split(','):
maintenance_list.append(str(maintenance).strip())
query = {
"output": "extend",
"searchByAny": True,
"selectGroups": ["name"],
"selectHosts": ["name"],
"selectTimeperiods": [
"timeperiodid",
"day",
"dayofweek",
"every",
"month",
"period",
"start_date",
"start_time",
"timeperiod_type",
],
"sortfield": "maintenanceid",
"sortorder": "ASC"
}
if maintenance_list:
query["maintenanceids"] = maintenance_list
#
# Get result from Zabbix API
#
try:
result = self.zapi.maintenance.get(**query)
logger.info('Command show_maintenance_periods executed')
except Exception as e:
logger.error('Problems getting maintenance periods information - %s', e)
self.generate_feedback('Error', 'Problems getting maintenance periods information')
return False
#
# Get the columns we want to show from result
#
for maintenance in result:
if self.output_format == 'json':
result_columns[result_columns_key] = {'maintenanceid': maintenance['maintenanceid'],
'name': maintenance['name'],
'timeperiods': maintenance['timeperiods'],
'hosts': maintenance['hosts'],
'groups': maintenance['groups']}
result_columns_key = result_columns_key + 1
else:
host_list = []
for host in maintenance['hosts']:
host_list.append(host['name'])
host_list.sort()
group_list = []
for group in maintenance['groups']:
group_list.append(group['name'])
group_list.sort()
for period in maintenance['timeperiods']:
result_columns[result_columns_key] = {1: maintenance['maintenanceid'],
2: '\n'.join(textwrap.wrap(maintenance['name'], 30)),
3: period['timeperiodid'],
4: period['day'],
5: format(int(period['dayofweek']), "07b"),
6: period['every'],
7: format(int(period['month']), "012b"),
8: datetime.datetime.utcfromtimestamp(float(period['start_date'])).strftime('%Y-%m-%dT%H:%M:%SZ'),
9: str(datetime.timedelta(seconds=int(period['start_time']))),
10: str(datetime.timedelta(seconds=int(period['period']))),
11: zabbix_cli.utils.get_maintenance_period_type(int(period['timeperiod_type'])),
12: '\n'.join(host_list),
13: '\n'.join(group_list)}
result_columns_key = result_columns_key + 1
#
# Generate output
#
self.generate_output(result_columns,
['DefID', 'DefName', 'PerID', 'Days', 'Dayweek', 'Every', 'Month', 'Start_date', 'Start_time', 'Period', 'PerType', 'Hostnames', 'Hostgroups'],
['DefName', 'Hostnames', 'Hostgroups'],
['DefID'],
ALL)
def do_show_zabbixcli_config(self, args):
'''
DESCRIPTION:
This command shows information about the
configuration used by this zabbix-cli instance.
COMMAND:
show_zabbixcli_config
'''
result_columns = {}
for i, filename in enumerate(self.conf.loaded_files):
result_columns[i] = {1: '* ' + filename}
#
# Generate output
#
self.generate_output(result_columns,
['Active configuration files'],
['Active configuration files'],
[''],
FRAME)
#
# Generate information with all the configuration parameters
#
result_columns = {}
for i, desc in enumerate(self.conf.iter_descriptors()):
result_columns[i] = {
1: desc.option,
2: self.conf.get(desc.section, desc.option),
}
#
# Generate output
#
self.generate_output(result_columns,
['Configuration parameter', 'Value'],
['Value'],
['Configuration parameter'],
FRAME)
def do_show_hostgroups(self, args):
'''
DESCRIPTION:
This command shows all hostgroups defined in the system.
COMMAND:
show_hostgroups
'''
cmd.Cmd.onecmd(self, 'show_hostgroup "*"')
def do_show_hostgroup(self, args):
'''
DESCRIPTION:
This command shows hostgroup information
COMMAND:
show_hostgroup [hostgroup]
[hostgroup]:
----------------
Hostgroup name. One can use wildcards.
'''
result_columns = {}
result_columns_key = 0
try:
arg_list = shlex.split(args)
except ValueError as e:
print('\n[ERROR]: ' + str(e) + '\n')
return False
#
# Command without parameters
#
if len(arg_list) == 0:
try:
print('--------------------------------------------------------')
hostgroup = input('# Hostgroup: ').strip()
print('--------------------------------------------------------')
except EOFError:
print('\n--------------------------------------------------------')
print('\n[Aborted] Command interrupted by the user.\n')
return False
#
# Command with parameters
#
elif len(arg_list) == 1:
hostgroup = arg_list[0].strip()
#
# Command with the wrong number of parameters
#
else:
self.generate_feedback('Error', ' Wrong number of parameters used.\n Type help or \\? to list commands')
return False
#
# Sanity check
#
if hostgroup == '':
self.generate_feedback('Error', 'Template value is empty')
return False
#
# Get result from Zabbix API
#
try:
result = self.zapi.hostgroup.get(output='extend',
search={'name': hostgroup},
searchWildcardsEnabled=True,
selectHosts=['host'],
sortfield='name',
sortorder='ASC')
logger.info('Command show_hostgroups executed')
except Exception as e:
logger.error('Problems getting hostgroups information - %s', e)
self.generate_feedback('Error', 'Problems getting hostgroups information')
return False
#
# Get the columns we want to show from result
#
for group in result:
if self.output_format == 'json':
result_columns[result_columns_key] = {'groupid': group['groupid'],
'name': group['name'],
'flags': zabbix_cli.utils.get_hostgroup_flag(int(group['flags'])),
'type': zabbix_cli.utils.get_hostgroup_type(int(group['internal'])),
'hosts': group['hosts']}
else:
host_list = []
for host in group['hosts']:
host_list.append(host['host'])
host_list.sort()
result_columns[result_columns_key] = {'1': group['groupid'],
'2': group['name'],
'3': zabbix_cli.utils.get_hostgroup_flag(int(group['flags'])),
'4': zabbix_cli.utils.get_hostgroup_type(int(group['internal'])),
'5': '\n'.join(textwrap.wrap(', '.join(host_list), 60))}
result_columns_key = result_columns_key + 1
#
# Generate output
#
self.generate_output(result_columns,
['GroupID', 'Name', 'Flag', 'Type', 'Hosts'],
['Name', 'Hosts'],
['GroupID'],
ALL)
def do_show_hosts(self, args):
'''
DESCRIPTION:
This command shows all hosts defined in the system.
COMMAND:
show_hosts
'''
cmd.Cmd.onecmd(self, 'show_host "*"')
def do_show_host(self, args):
'''
DESCRIPTION:
This command shows hosts information
COMMAND:
show_host [HostID / Hostname]
[Filter]
[HostID / Hostname]:
-------------------
One can search by HostID or by Hostname. One can use wildcards
if we search by Hostname
[Filter]:
--------
* Zabbix agent: 'available': 0=Unknown
1=Available
2=Unavailable
* Maintenance: 'maintenance_status': 0:No maintenance
1:In progress
* Status: 'status': 0:Monitored
1: Not monitored
e.g.: Show all hosts with Zabbix agent: Available AND Status: Monitored:
show_host * "'available':'1','status':'0'"
'''
result_columns = {}
result_columns_key = 0
try:
arg_list = shlex.split(args)
except ValueError as e:
print('\n[ERROR]: ' + str(e) + '\n')
return False
#
# Command without parameters
#
if len(arg_list) == 0:
try:
print('--------------------------------------------------------')
host = input('# Host: ').strip()
_filter = input('# Filter: ').strip()
print('--------------------------------------------------------')
except EOFError:
print('\n--------------------------------------------------------')
print('\n[Aborted] Command interrupted by the user.\n')
return False
#
# Command without filters attributes
#
elif len(arg_list) == 1:
host = arg_list[0].strip()
_filter = ''
#
# Command with filters attributes
#
elif len(arg_list) == 2:
host = arg_list[0].strip()
_filter = arg_list[1].strip()
#
# Command with the wrong number of parameters
#
else:
self.generate_feedback('Error', ' Wrong number of parameters used.\n Type help or \\? to list commands')
return False
query = {
"output": "extend",
"selectParentTemplates": [
"templateid",
"name"
],
"selectGroups": [
"groupid",
"name"
],
"selectApplications": [
"name"
],
"sortfield": "host",
"sortorder": "ASC",
"searchWildcardsEnabled": True,
"filter": {
}
}
if host.isdigit():
query["hostids"] = host
else:
query["search"] = {"host": host}
if _filter:
try:
filter_items = _filter.split(",")
for filter_item in filter_items:
key, value = [s.strip("'\"") for s in filter_item.split(":")]
query["filter"][key] = value
except ValueError:
self.generate_feedback("Error", "Unable to parse filter")
return False
#
# Get result from Zabbix API
#
try:
result = self.zapi.host.get(**query)
logger.info('Command show_host executed.')
except Exception as e:
logger.error('Problems getting host information - %s', e)
self.generate_feedback('Error', 'Problems getting host information')
return False
#
# Get the columns we want to show from result
#
for host in result:
proxy = self.zapi.proxy.get(proxyids=host['proxy_hostid'])
proxy_name = proxy[0]['host'] if proxy else ""
if self.output_format == 'json':
result_columns[result_columns_key] = {'hostid': host['hostid'],
'host': host['host'],
'groups': host['groups'],
'templates': host['parentTemplates'],
'zabbix_agent': zabbix_cli.utils.get_zabbix_agent_status(int(host['available'])),
'maintenance_status': zabbix_cli.utils.get_maintenance_status(int(host['maintenance_status'])),
'status': zabbix_cli.utils.get_monitoring_status(int(host['status'])),
'proxy': proxy_name}
else:
hostgroup_list = []
template_list = []
for hostgroup in host['groups']:
hostgroup_list.append(hostgroup['name'])
for template in host['parentTemplates']:
template_list.append(template['name'])
hostgroup_list.sort()
template_list.sort()
result_columns[result_columns_key] = {'1': host['hostid'],
'2': host['host'],
'3': '\n'.join(hostgroup_list),
'4': '\n'.join(template_list),
'5': zabbix_cli.utils.get_zabbix_agent_status(int(host['available'])),
'6': zabbix_cli.utils.get_maintenance_status(int(host['maintenance_status'])),
'7': zabbix_cli.utils.get_monitoring_status(int(host['status'])),
'8': proxy_name}
result_columns_key = result_columns_key + 1
#
# Generate output
#
self.generate_output(result_columns,
['HostID', 'Name', 'Hostgroups', 'Templates', 'Zabbix agent', 'Maintenance', 'Status', 'Proxy'],
['Name', 'Hostgroups', 'Templates'],
['HostID'],
ALL)
def do_update_host_inventory(self, args):
'''
DESCRIPTION:
This command updates one hosts' inventory
COMMAND:
update_host_inventory [hostname]
[inventory_key]
[inventory value]
Inventory key is not the same as seen in web-gui. To
look at possible keys and their current values, use
"zabbix-cli --use-json-format show_host_inventory <hostname>"
'''
try:
arg_list = shlex.split(args)
except ValueError as e:
print('\n[ERROR]: ' + str(e) + '\n')
return False
#
# Command without parameters
#
if len(arg_list) == 0:
try:
print('--------------------------------------------------------')
host = input('# Host: ')
inventory_key = input('# Inventory key: ')
inventory_value = input('# Inventory value: ')
print('--------------------------------------------------------')
except EOFError:
print('\n--------------------------------------------------------')
print('\n[Aborted] Command interrupted by the user.\n')
return False
#
# Command without inventory_key and inventory value attributes
#
elif len(arg_list) == 1:
host = arg_list[0]
inventory_key = input('# Inventory key: ')
inventory_value = input('# Inventory value: ')
#
# Command cithout inventory value attribute
#
elif len(arg_list) == 2:
host = arg_list[0]
inventory_key = arg_list[1]
inventory_value = input('# Inventory value: ')
elif len(arg_list) == 3:
host = arg_list[0]
inventory_key = arg_list[1]
inventory_value = arg_list[2]
#
# Command with the wrong number of parameters
#
else:
self.generate_feedback('Error', ' Wrong number of parameters used.\n Type help or \\? to list commands')
return False
try:
host_id = str(self.get_host_id(host))
except Exception as e:
print('\n[ERROR]: ' + str(e) + '\n')
return False
#
# Generate query
#
if host_id == '0':
self.generate_feedback('Error', 'Host id for "' + host + '" not found')
return False
query = {
"hostid": host_id,
"inventory": {
inventory_key: inventory_value
}
}
#
# Get result from Zabbix API
#
try:
self.zapi.host.update(**query)
logger.info('Command update_host_inventory executed [%s] [%s] [%s].', host, inventory_key, inventory_value)
except Exception as e:
logger.error('Problems updating host inventory information - %s', e)
self.generate_feedback('Error', 'Problems updating host inventory information')
return False
def do_show_host_inventory(self, args):
'''
DESCRIPTION:
This command shows hosts inventory
COMMAND:
show_host_inventory [Hostname]
[Hostname]:
----------
Hostname.
'''
result_columns = {}
result_columns_key = 0
try:
arg_list = shlex.split(args)