Esta es una traducción de la página de documentación original en español. Ayúdanos a mejorarla.

#16 Agente HTTP

Visión general

Este tipo de elemento permite el sondeo de datos utilizando el protocolo HTTP/HTTPS. La captura también es posible utilizando el remitente de Zabbix o el protocolo de remitente de Zabbix.

La verificación de elementos HTTP es ejecutada por el servidor Zabbix. Sin embargo, cuando los anfitriones son supervisado por un proxy Zabbix, el proxy ejecuta las comprobaciones de elementos HTTP.

Las comprobaciones de elementos HTTP no requieren que se ejecute ningún agente en un host. supervisado.

El agente HTTP admite tanto HTTP como HTTPS. Zabbix seguirá opcionalmente redireccionamientos (consulte la opción Seguir redireccionamientos a continuación). Número máximo de redirects está codificado de forma rígida a 10 (usando la opción cURL CURLOPT_MAXREDIRS).

Consulte también problemas conocidos para cuando se utiliza el protocolo HTTPS.

El servidor/proxy Zabbix debe configurarse inicialmente con soporte cURL (libcurl).

Configuration

To configure an HTTP item:

  • Go to: ConfigurationHosts
  • Click on Items in the row of the host
  • Click on Create item
  • Enter parameters of the item in the form

All mandatory input fields are marked with a red asterisk.

The fields that require specific information for HTTP items are:

Type Select HTTP agent here.
Key Enter a unique item key.
URL URL to connect to and retrieve data. For example:
https://www.example.com
http://www.example.com/download
Domain names can be specified in Unicode characters. They are automatically punycode-converted to ASCII when executing the HTTP check.
The Parse button can be used to separate optional query fields (like ?name=Admin&password=mypassword) from the URL, moving the attributes and values into Query fields for automatic URL-encoding.
Limited to 2048 characters.
Supported macros: {HOST.IP}, {HOST.CONN}, {HOST.DNS}, {HOST.HOST}, {HOST.NAME}, {ITEM.ID}, {ITEM.KEY}, {ITEM.KEY.ORIG}, user macros, low-level discovery macros.
This sets the CURLOPT_URL cURL option.
Query fields Variables for the URL (see above).
Specified as attribute and value pairs.
Values are URL-encoded automatically. Values from macros are resolved and then URL-encoded automatically.
Supported macros: {HOST.IP}, {HOST.CONN}, {HOST.DNS}, {HOST.HOST}, {HOST.NAME}, {ITEM.ID}, {ITEM.KEY}, {ITEM.KEY.ORIG}, user macros, low-level discovery macros.
This sets the CURLOPT_URL cURL option.
Request type Select request method type: GET, POST, PUT or HEAD
Timeout Zabbix will not spend more than the set amount of time on processing the URL (1-60 seconds). Actually this parameter defines the maximum time for making a connection to the URL and maximum time for performing an HTTP request. Therefore, Zabbix will not spend more than 2 x Timeout seconds on one check.
Time suffixes are supported, e.g. 30s, 1m.
Supported macros: user macros, low-level discovery macros.
This sets the CURLOPT_TIMEOUT cURL option.
Request body type Select the request body type:
Raw data - custom HTTP request body, macros are substituted but no encoding is performed
JSON data - HTTP request body in JSON format. Macros can be used as string, number, true and false; macros used as strings must be enclosed in double quotes. Values from macros are resolved and then escaped automatically. If "Content-Type" is not specified in headers then it will default to "Content-Type: application/json"
XML data - HTTP request body in XML format. Macros can be used as a text node, attribute or CDATA section. Values from macros are resolved and then escaped automatically in a text node and attribute. If "Content-Type" is not specified in headers then it will default to "Content-Type: application/xml"
Note that selecting XML data requires libxml2.
Request body Enter the request body.
Supported macros: {HOST.IP}, {HOST.CONN}, {HOST.DNS}, {HOST.HOST}, {HOST.NAME}, {ITEM.ID}, {ITEM.KEY}, {ITEM.KEY.ORIG}, user macros, low-level discovery macros.
Headers Custom HTTP headers that will be sent when performing a request.
Specified as attribute and value pairs.
Supported macros: {HOST.IP}, {HOST.CONN}, {HOST.DNS}, {HOST.HOST}, {HOST.NAME}, {ITEM.ID}, {ITEM.KEY}, {ITEM.KEY.ORIG}, user macros, low-level discovery macros.
This sets the CURLOPT_HTTPHEADER cURL option.
Required status codes List of expected HTTP status codes. If Zabbix gets a code which is not in the list, the item will become unsupported. If empty, no check is performed.
For example: 200,201,210-299
Supported macros in the list: user macros, low-level discovery macros.
This uses the CURLINFO_RESPONSE_CODE cURL option.
Follow redirects Mark the checkbox to follow HTTP redirects.
This sets the CURLOPT_FOLLOWLOCATION cURL option.
Retrieve mode Select the part of response that must be retrieved:
Body - body only
Headers - headers only
Body and headers - body and headers
Convert to JSON Headers are saved as attribute and value pairs under the "header" key.
If 'Content-Type: application/json' is encountered then body is saved as an object, otherwise it is stored as string, for example:
HTTP proxy You can specify an HTTP proxy to use, using the format [protocol://][username[:password]@]proxy.example.com[:port].
The optional protocol:// prefix may be used to specify alternative proxy protocols (e.g. https, socks4, socks5; see documentation; the protocol prefix support was added in cURL 7.21.7). With no protocol specified, the proxy will be treated as an HTTP proxy. If you specify the wrong protocol, the connection will fail and the item will become unsupported.
By default, 1080 port will be used.
If specified, the proxy will overwrite proxy related environment variables like http_proxy, HTTPS_PROXY. If not specified, the proxy will not overwrite proxy-related environment variables. The entered value is passed on "as is", no sanity checking takes place.
Note that only simple authentication is supported with HTTP proxy.
Supported macros: {HOST.IP}, {HOST.CONN}, {HOST.DNS}, {HOST.HOST}, {HOST.NAME}, {ITEM.ID}, {ITEM.KEY}, {ITEM.KEY.ORIG}, user macros, low-level discovery macros.
This sets the CURLOPT_PROXY cURL option.
HTTP authentication Authentication type:
None - no authentication used.
Basic - basic authentication is used.
NTLM - NTLM (Windows NT LAN Manager) authentication is used.
Kerberos - Kerberos authentication is used. See also: Configuring Kerberos with Zabbix.
Digest - Digest authentication is used.
Selecting an authentication method will provide two additional fields for entering a user name and password, where user macros and low-level discovery macros are supported.
This sets the CURLOPT_HTTPAUTH cURL option.
SSL verify peer Mark the checkbox to verify the SSL certificate of the web server. The server certificate will be automatically taken from system-wide certificate authority (CA) location. You can override the location of CA files using Zabbix server or proxy configuration parameter SSLCALocation.
This sets the CURLOPT_SSL_VERIFYPEER cURL option.
SSL verify host Mark the checkbox to verify that the Common Name field or the Subject Alternate Name field of the web server certificate matches.
This sets the CURLOPT_SSL_VERIFYHOST cURL option.
SSL certificate file Name of the SSL certificate file used for client authentication. The certificate file must be in PEM1 format. If the certificate file contains also the private key, leave the SSL key file field empty. If the key is encrypted, specify the password in SSL key password field. The directory containing this file is specified by Zabbix server or proxy configuration parameter SSLCertLocation.
Supported macros: {HOST.IP}, {HOST.CONN}, {HOST.DNS}, {HOST.HOST}, {HOST.NAME}, {ITEM.ID}, {ITEM.KEY}, {ITEM.KEY.ORIG}, user macros, low-level discovery macros.
This sets the CURLOPT_SSLCERT cURL option.
SSL key file Name of the SSL private key file used for client authentication. The private key file must be in PEM1 format. The directory containing this file is specified by Zabbix server or proxy configuration parameter SSLKeyLocation.
Supported macros: {HOST.IP}, {HOST.CONN}, {HOST.DNS}, {HOST.HOST}, {HOST.NAME}, {ITEM.ID}, {ITEM.KEY}, {ITEM.KEY.ORIG}, user macros, low-level discovery macros.
This sets the CURLOPT_SSLKEY cURL option.
SSL key password SSL private key file password.
Supported macros: user macros, low-level discovery macros.
This sets the CURLOPT_KEYPASSWD cURL option.
Enable trapping With this checkbox marked, the item will also function as trapper item and will accept data sent to this item by Zabbix sender or using Zabbix sender protocol.
Allowed hosts Visible only if Enable trapping checkbox is marked.
List of comma delimited IP addresses, optionally in CIDR notation, or hostnames.
If specified, incoming connections will be accepted only from the hosts listed here.
If IPv6 support is enabled then '127.0.0.1', '::127.0.0.1', '::ffff:127.0.0.1' are treated equally and '::/0' will allow any IPv4 or IPv6 address.
'0.0.0.0/0' can be used to allow any IPv4 address.
Note, that "IPv4-compatible IPv6 addresses" (0000::/96 prefix) are supported but deprecated by RFC4291.
Example: Server=127.0.0.1, 192.168.1.0/24, 192.168.3.1-255, 192.168.1-10.1-255, ::1,2001:db8::/32, zabbix.domain
Spaces and user macros are allowed in this field.
Host macros: {HOST.HOST}, {HOST.NAME}, {HOST.IP}, {HOST.DNS}, {HOST.CONN} are allowed in this field.

If the HTTP proxy field is left empty, another way for using an HTTP proxy is to set proxy-related environment variables.

For HTTP - set the http_proxy environment variable for the Zabbix server user. For example:
http_proxy=http://proxy_ip:proxy_port.

For HTTPS - set the HTTPS_PROXY environment variable. For example:
HTTPS_PROXY=http://proxy_ip:proxy_port. More details are available by running a shell command: # man curl.

[1] Zabbix supports certificate and private key files in PEM format only. In case you have your certificate and private key data in PKCS #12 format file (usually with extension *.p12 or *.pfx) you may generate the PEM file from it using the following commands:

openssl pkcs12 -in ssl-cert.p12 -clcerts -nokeys -out ssl-cert.pem
       openssl pkcs12 -in ssl-cert.p12 -nocerts -nodes  -out ssl-cert.key

Ejemplos

Example 1

Send simple GET requests to retrieve data from services such as Elasticsearch:

  • Create a GET item with URL: localhost:9200/?pretty
  • Notice the response:
{
         "name" : "YQ2VAY-",
         "cluster_name" : "elasticsearch",
         "cluster_uuid" : "kH4CYqh5QfqgeTsjh2F9zg",
         "version" : {
           "number" : "6.1.3",
           "build_hash" : "af51318",
           "build_date" : "2018-01-26T18:22:55.523Z",
           "build_snapshot" : false,
           "lucene_version" : "7.1.0",
           "minimum_wire_compatibility_version" : "5.6.0",
           "minimum_index_compatibility_version" : "5.0.0"
         },
         "tagline" : "You know, for search"
       }
  • Now extract the version number using a JSONPath preprocessing step: $.version.number
Ejemplo 2

Envíe solicitudes POST simples para recuperar datos de servicios como Búsqueda elástica:

  • Crear un elemento POST con URL: http://localhost:9200/str/values/_search?scroll=10s
  • Configure el siguiente cuerpo POST para obtener la carga del procesador (1 promedio mínimo por núcleo)
{
           "consulta": {
               "bool": {
                   "deber": [{
                       "juego": {
                           "ítemid": 28275
                       }
                   }],
                   "filtro": [{
                       "rango": {
                           "reloj": {
                               "gt": 1517565836,
                               "lte": 1517566137
                           }
                       }
                   }]
               }
           }
       }
  • Recibió:
{
           "_scroll_id": "DnF1ZXJ5VGhlbkZldGNoBQAAAAAAAAAkFllRMlZBWS1UU1pxTmdEeGVwQjRBTFEAAAAAAAAAJRZZUTJWQVktVFNacU5nRHhlcEI0QUxRAAAAAAAAACYWWVEyVkFZLVRTWnFOZ0R4ZXBCNEFMUQAAAAAAAAAnFllRMlZBWS1UU1pxTmdEeGVwQjRBTFEAAAAAAAAAKBZZUTJWQVktVFNacU5nRHhlcEI0QUxR",
           "tomó": 18,
           "timed_out": falso,
           "_fragmentos": {
               "totales": 5,
               "exitoso": 5,
               "omitido": 0,
               "fallido": 0
           },
           "golpes": {
               "totales": 1,
               "puntuación_máxima": 1.0,
               "golpes": [{
                   "_index": "dbl",
                   "_type": "valores",
                   "_id": "dqX9VWEBV6sEKSMyk6sw",
                   "_puntuación": 1.0,
                   "_fuente": {
                       "ítemid": 28275,
                       "valor": "0.138750",
                       "reloj": 1517566136,
                       "ns": 25388713,
                       "ttl": 604800
                   }
               }]
           }
       }
  • Ahora use un paso de preprocesamiento JSONPath para obtener el valor del elemento: $.hits.hits[0]._source.value
Ejemplo 3

Comprobando si la API de Zabbix está viva, usando apiinfo.version.

  • Configuración del artículo:

Tenga en cuenta el uso del método POST con datos JSON, configurando encabezados de solicitud y pidiendo devolver solo encabezados:

  • Preprocesamiento del valor del elemento con expresión regular para obtener el código HTTP:

  • Comprobando el resultado en Últimos datos:

Ejemplo 4

Recuperación de información meteorológica conectándose a Openweathermap servicio público.

  • Configure un elemento maestro para la recopilación masiva de datos en un solo JSON:

Tenga en cuenta el uso de macros en los campos de consulta. Consulte el Openweathermap API para saber cómo llenarlos.

Ejemplo de JSON devuelto en respuesta al agente HTTP:

{
           "cuerpo": {
               "coord": {
                   "lón": 40.01,
                   "lat": 56,11
               },
               "clima": [{
                   "identificación": 801,
                   "principal": "Nubes",
                   "descripcion": "pocas nubes",
                   "icono": "02n"
               }],
               "base": "estaciones",
               "principal": {
                   "temperatura": 15.14,
                   "presión": 1012.6,
                   "humedad": 66,
                   "temp_min": 15.14,
                   "temp_max": 15.14,
                   "nivel_del_mar": 1030.91,
                   "nivel_nivel": 1012.6
               },
               "viento": {
                   "velocidad": 1.86,
                   "grado": 246.001
               },
               "nubes": {
                   "todos": 20
               },
               "dt": 1526509427,
               "sistema": {
                   "mensaje": 0.0035,
                   "país": "RU",
                   "amanecer": 1526432608,
                   "puesta de sol": 1526491828
               },
               "id": 487837,
               "nombre": "Stavrovo",
               "bacalao": 200
           }
       }

La siguiente tarea es configurar elementos dependientes que extraen datos del JSON.

  • Configure un elemento dependiente de la muestra para la humedad:

Otras métricas meteorológicas como 'Temperatura' se agregan en el mismo manera.

  • Preprocesamiento de valor de elemento dependiente de muestra con JSONPath:

  • Consultar el resultado de los datos meteorológicos en Últimos datos:

Ejemplo 5

Conectarse a la página de estado de Nginx y obtener sus métricas a granel.

  • Configurar Nginx siguiendo el [oficial guía] (https://nginx.ru/en/docs/http/ngx_http_stub_status_module.html).
  • Configure un elemento maestro para la recopilación masiva de datos:

Ejemplo de salida de estado de stub de Nginx:

Conexiones activas: 1 Conexiones activas:
       el servidor acepta solicitudes manejadas
        52 52 52
       Lectura: 0 Escritura: 1 Espera: 0

La siguiente tarea es configurar elementos dependientes que extraen datos.

  • Configure un elemento dependiente de muestra para solicitudes por segundo:

  • Preprocesamiento de valor de elemento dependiente de muestra con expresión regular el servidor acepta solicitudes manejadas\s+([0-9]+) ([0-9]+) ([0-9]+):

  • Verifique el resultado completo del módulo stub en Últimos datos: