0
# Zabbix API Interface
1
2
Complete Python interface to Zabbix's JSON-RPC API providing authentication management, dynamic method dispatch, and comprehensive error handling for all Zabbix monitoring operations including host management, configuration, and data retrieval.
3
4
## Capabilities
5
6
### ZabbixAPI Class
7
8
Main API client class that handles authentication, session management, and provides access to all Zabbix API methods through dynamic method dispatch.
9
10
```python { .api }
11
class ZabbixAPI:
12
def __init__(self, url=None, use_authenticate=False, use_basic_auth=False, user=None, password=None):
13
"""
14
Initialize ZabbixAPI client.
15
16
Parameters:
17
- url (str, optional): Zabbix server URL (e.g., 'https://zabbix.example.com')
18
- use_authenticate (bool, optional): Use user.authenticate instead of user.login (default: False)
19
- use_basic_auth (bool, optional): Enable HTTP basic authentication (default: False)
20
- user (str, optional): Username for authentication
21
- password (str, optional): Password for authentication
22
"""
23
```
24
25
#### Authentication and Session Management
26
27
```python { .api }
28
def api_version(self):
29
"""
30
Get Zabbix API version.
31
32
Returns:
33
str: API version string
34
"""
35
36
def _login(self, user='', password=''):
37
"""
38
Authenticate with Zabbix server (internal method).
39
40
Parameters:
41
- user (str, optional): Username (default: '')
42
- password (str, optional): Password (default: '')
43
44
Returns:
45
None: Sets self.auth attribute with authentication token
46
47
Raises:
48
ZabbixAPIException: If authentication fails
49
"""
50
51
def _logout(self):
52
"""
53
Logout from Zabbix server and invalidate session (internal method).
54
55
Returns:
56
bool: True if successful
57
"""
58
```
59
60
#### Core API Methods
61
62
```python { .api }
63
def do_request(self, method, params=None):
64
"""
65
Make raw JSON-RPC request to Zabbix API.
66
67
Parameters:
68
- method (str): API method name (e.g., 'host.get', 'user.login')
69
- params (dict, optional): Method parameters
70
71
Returns:
72
dict: API response result
73
74
Raises:
75
ZabbixAPIException: If API returns error
76
"""
77
78
def get_id(self, item_type, item=None, with_id=False, hostid=None, **args):
79
"""
80
Get object IDs by name or other criteria.
81
82
Parameters:
83
- item_type (str): Object type ('host', 'hostgroup', 'template', etc.)
84
- item (str, optional): Object name to search for
85
- with_id (bool, optional): Return full object data instead of just IDs
86
- hostid (str, optional): Host ID for item-specific searches
87
- **args: Additional filter parameters
88
89
Returns:
90
list: Object IDs or full object data
91
"""
92
```
93
94
#### Context Manager Support
95
96
```python { .api }
97
def __enter__(self):
98
"""
99
Context manager entry - returns self for with statements.
100
101
Returns:
102
ZabbixAPI: Self instance
103
"""
104
105
def __exit__(self, exc_type, exc_val, exc_tb):
106
"""
107
Context manager exit - automatically logout on context exit.
108
109
Parameters:
110
- exc_type: Exception type (if any)
111
- exc_val: Exception value (if any)
112
- exc_tb: Exception traceback (if any)
113
"""
114
```
115
116
#### Dynamic Method Access
117
118
The ZabbixAPI class provides dynamic access to all Zabbix API methods through attribute access:
119
120
```python { .api }
121
def __getattr__(self, attr):
122
"""
123
Provide dynamic access to API method groups.
124
125
Parameters:
126
- attr (str): API method group (e.g., 'host', 'user', 'item')
127
128
Returns:
129
ZabbixAPIObjectClass: Method dispatcher for the group
130
"""
131
```
132
133
### ZabbixAPIObjectClass
134
135
Internal class that handles dynamic method dispatch for API method groups. Created automatically when accessing API method groups (e.g., `zapi.host`, `zapi.user`).
136
137
```python { .api }
138
class ZabbixAPIObjectClass:
139
def __init__(self, group, parent):
140
"""
141
Initialize method group dispatcher.
142
143
Parameters:
144
- group (str): API method group name (e.g., 'host', 'user')
145
- parent (ZabbixAPI): Parent ZabbixAPI instance
146
"""
147
148
def __getattr__(self, name):
149
"""
150
Dynamically create API method calls.
151
152
Parameters:
153
- name (str): API method name (e.g., 'get', 'create', 'update')
154
155
Returns:
156
function: Callable that executes the API method
157
"""
158
```
159
160
This class enables the fluent API pattern where `zapi.host.get()` translates to a `host.get` API call.
161
162
### Usage Examples
163
164
Basic authentication and API calls:
165
166
```python
167
from pyzabbix import ZabbixAPI, ZabbixAPIException
168
169
# Initialize and authenticate
170
zapi = ZabbixAPI('https://zabbix.example.com')
171
zapi.login('Admin', 'zabbix')
172
173
try:
174
# Get API version
175
version = zapi.api_version()
176
print(f"Zabbix API version: {version}")
177
178
# Get all hosts using dynamic method
179
hosts = zapi.host.get(output='extend')
180
181
# Get specific host by name
182
host_id = zapi.get_id('host', 'server01')
183
184
# Raw API request
185
templates = zapi.do_request('template.get', {
186
'output': ['templateid', 'name'],
187
'sortfield': 'name'
188
})
189
190
# Create host group
191
result = zapi.hostgroup.create(name='My Host Group')
192
193
except ZabbixAPIException as e:
194
print(f"API Error: {e}")
195
finally:
196
zapi.user.logout()
197
```
198
199
Using context manager for automatic logout:
200
201
```python
202
from pyzabbix import ZabbixAPI
203
204
with ZabbixAPI('https://zabbix.example.com', user='Admin', password='zabbix') as zapi:
205
# Get monitored hosts
206
hosts = zapi.host.get(
207
monitored_hosts=1,
208
output=['hostid', 'host', 'name', 'status']
209
)
210
211
# Get items for a specific host
212
items = zapi.item.get(
213
hostids=hosts[0]['hostid'],
214
output=['itemid', 'name', 'key_', 'lastvalue']
215
)
216
217
# Automatic logout when exiting context
218
```
219
220
Enabling logging for debugging:
221
222
```python
223
import logging
224
import sys
225
from pyzabbix import ZabbixAPI
226
227
# Configure logging
228
logger = logging.getLogger("pyzabbix")
229
logger.setLevel(logging.DEBUG)
230
handler = logging.StreamHandler(sys.stdout)
231
logger.addHandler(handler)
232
233
zapi = ZabbixAPI('https://zabbix.example.com', user='Admin', password='zabbix')
234
# Requests and responses will be logged (with passwords masked)
235
hosts = zapi.host.get(output='extend')
236
```
237
238
### Error Handling
239
240
```python { .api }
241
class ZabbixAPIException(Exception):
242
"""
243
Custom exception for Zabbix API errors.
244
245
Attributes:
246
- error (dict): Full error details from API response
247
- message (str): Error message
248
- code (int): Error code
249
- data (str): Additional error data
250
- json (str): Sanitized JSON request (passwords masked)
251
"""
252
def __init__(self, error):
253
"""
254
Initialize exception with error details.
255
256
Parameters:
257
- error (dict): Error information from API response
258
"""
259
```
260
261
Common error codes:
262
- `32602`: Invalid params (e.g., object already exists)
263
- `32500`: No permissions
264
- `-32602`: Invalid method parameters
265
- `-32500`: Application error (user not logged in, permission denied)
266
267
### API Method Groups
268
269
The ZabbixAPI class provides access to all Zabbix API method groups through dynamic attributes:
270
271
- `zapi.host.*` - Host management (get, create, update, delete)
272
- `zapi.hostgroup.*` - Host group management
273
- `zapi.item.*` - Item management
274
- `zapi.trigger.*` - Trigger management
275
- `zapi.user.*` - User management (login, logout, get, create)
276
- `zapi.template.*` - Template management
277
- `zapi.graph.*` - Graph management
278
- `zapi.action.*` - Action management
279
- `zapi.alert.*` - Alert management
280
- `zapi.event.*` - Event management
281
- `zapi.maintenance.*` - Maintenance management
282
- `zapi.map.*` - Network map management
283
- `zapi.screen.*` - Screen management
284
- `zapi.script.*` - Script management
285
- `zapi.service.*` - IT service management
286
- `zapi.mediatype.*` - Media type management
287
- `zapi.proxy.*` - Proxy management
288
289
Each method group supports the standard CRUD operations where applicable (get, create, update, delete) plus method-specific operations.
290
291
### Utility Functions
292
293
```python { .api }
294
@staticmethod
295
def cred_to_base64(user, password):
296
"""
297
Create base64-encoded credentials for HTTP basic authentication.
298
299
Parameters:
300
- user (str): Username
301
- password (str): Password
302
303
Returns:
304
str: Base64-encoded credentials string
305
"""
306
307
def ssl_context_compat(func):
308
"""
309
Decorator to handle SSL context compatibility across Python versions.
310
311
This decorator wraps urllib functions to disable SSL certificate verification
312
for self-signed certificates, handling version differences between Python 2.7.9+
313
and Python 3.4.3+.
314
315
Parameters:
316
- func (function): Function to wrap (typically urllib2.urlopen)
317
318
Returns:
319
function: Wrapped function with SSL context handling
320
"""
321
```
322
323
These utilities support advanced authentication scenarios and SSL handling across different Python versions.