A
A
Anton2019-02-26 21:29:30
Python
Anton, 2019-02-26 21:29:30

How to generate JSON with python with sequence key to discover Zabbix LLD TOP 5 processes from memory?

I am trying to generate JSON with python with sequence key to discover Zabbix LLD TOP 5 processes from memory

#!/usr/bin/python

import subprocess
import json

s = subprocess.Popen(["ps axho comm --sort -rss | head -5"], shell=True, stdout=subprocess.PIPE).stdout
service_states = s.read().splitlines()

count = 0
data = {"data":{}}
for i in service_states:
  count += 1
  key = "{#TOPMEMNAME" + str(count) + "}"
  data["data"][key] = i

json_data = json.dumps(data)
print(json_data)

It turns out JSON not accepted by Zabbix
{
  "data": {
    "{#TOPMEMNAME2}": "node",
    "{#TOPMEMNAME1}": "mongod",
    "{#TOPMEMNAME4}": "ffmpeg",
    "{#TOPMEMNAME3}": "kubelet",
    "{#TOPMEMNAME5}": "dockerd"
  }
}

And here is the code that zabbix accepts.
{
    "data": [{
            "{#TOPMEMNAME1}": "mongod"
        },
        {
            "{#TOPMEMNAME2}": "node"
        },
        {
            "{#TOPMEMNAME3}": "kubelet"
        },
        {
            "{#TOPMEMNAME4}": "ffmpeg"
        },
        {
            "{#TOPMEMNAME5}": "dockerd"
        }
    ]
}

How to change python code so zabbix will accept json?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Ratkin, 2019-02-26
Patsev @chemtech

And if so

#!/usr/bin/env python3

import os
import json

s = os.popen("ps axho comm --sort -rss | head -5").read()

service_states = s.split()

count = 0
data = {}

for i in service_states:
    count += 1
    key = "{#TOPMEMNAME" + str(count) + "}"
    data.setdefault("data", []).append({key:i})

print(json.dumps(data, sort_keys=True, indent=2))

Conclusion:
{
  "data": [
    {
      "{#TOPMEMNAME1}": "python3"
    },
    {
      "{#TOPMEMNAME2}": "bash"
    },
    {
      "{#TOPMEMNAME3}": "ps"
    },
    {
      "{#TOPMEMNAME4}": "head"
    },
    {
      "{#TOPMEMNAME5}": "sh"
    }
  ]
}

He screwed up a little.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question