Hi all, I am stuck to get a python script to work, I need to receive metrics from a query to a remote server and send them through zabbix_send to a prototype item in zabbix. Everything seemed to be perfect but the problem is that when receiving the values it sends them in the key items (creating new items) instead of sending them as values, that is to say, I am connecting correctly and receiving the metrics that I want but I am not assigning them as values to my items, I imagine that I am not sending the values that I receive to my macros but I do not know where to make this assignment. I have checked many times my code and reviewed the logic of the LLD but I am at a point of no return, someone please help me.
HTML Code:
from pyzabbix import ZabbixMetric, ZabbixSender
from fabric import Connection
import time
import datetime
import pytz
import re
import yaml
import sys
import json
def sendZabbix(server, port, data):
# Configura la dirección y el puerto del servidor Zabbix
zabbix_server = server
zabbix_port = port
# Create a dictionary to hold the discovery data
discovery_data = {'data': [],}
for i in data:
discovery_item = {
'{#REPLID}': i[0],
'{#REPLNAME}': i[1],
'{#REPLCLUSTER}': i[2],
'{#REPLFROZENDURATION}': str(i[4].total_seconds()),
'{#REPLMASTER}': i[5],
'{#REPLSTATUS}': i[6],
}
discovery_data['data'].append(discovery_item)
# Convert the dictionary to a JSON string
json_data = json.dumps(discovery_data)
# Create ZabbixMetric to discovery item
discovery_metric = ZabbixMetric(host, 'repl.discovery', json_data)
# Create a ZabbixSender instance and send the discovery metric
zabbix_sender = ZabbixSender(zabbix_server=zabbix_server, zabbix_port=10051)
print(discovery_metric)
result = zabbix_sender.send([discovery_metric])
print(result)
# Show result
if result.failed:
print(f"Error al enviar métricas de descubrimiento: {result.failed}")
else:
print("Métricas de descubrimiento enviadas exitosamente.")
def runnerReplic(host, user, pssw):
# Establish a conection SSH
conn = Connection(host=host, user=user, connect_kwargs={"password": pssw})
# Execute command
timezone = conn.run("showtimezone -delim :", hide=True)
frezee_time = conn.run("lsrcconsistgrp -delim ,", hide=True)
# Print output
print(frezee_time.stdout)
match = re.search(r'\d+:(\w+/\w+)', timezone.stdout)
# Close SSH
conn.close()
original_timezone = pytz.timezone("UTC")
target_timezone = pytz.timezone(match.group(1))
# Split the lines
lineas = (frezee_time.stdout).split('\n')
data = []
# Iterar a través de las líneas, excluyendo la primera (que contiene encabezados)
for linea in lineas[1:]:
elementos = linea.split(',') # Dividir la línea en elementos separados por comas
if len(elementos) >= 2:
id = elementos[0]
name = elementos[1]
cluster_name = elementos[5]
master_name = elementos[3]
status = elementos[6]
freeze_times = target_timezone.localize(datetime.datetime.strptime(elementos[-1], "%Y/%m/%d/%H/%M/%S"))
freeze_times = freeze_times.astimezone(original_timezone)
now = datetime.datetime.now(original_timezone).replace(microsecond=0)
data.append([id,name,cluster_name,freeze_times,now-freeze_times,master_name,status])
return data
def main():
global host
host = sys.argv[1]
# Credentials from the YAML
conf = yaml.load(open('path/configuration.yml'), Loader=yaml.SafeLoader)
user = conf['svc']['user']
password = conf['svc']['password']
data = runnerReplic(host, user, password)
zabbix_server = 'localhost'
port = 10050
sendZabbix(zabbix_server, port, data)
if __name__ == "__main__":
main()
Comment