文章 85
评论 72
浏览 87715
python获取数据实现echarts出图

python获取数据实现echarts出图

一、 python3 + echarts

1.1. python3 获取数据展示无线节点图例:

1.1.1 通过 snmp 获取源数据

#!/bin/env python3
import json
import subprocess
import os
User_list = []
CMD_num = "snmpwalk -v 2c -c limi@2018  10.200.250.5 1.3.6.1.4.1.2011.6.139.13.3.10.1.5 | wc -l"  #AP总数
Num = int(subprocess.getoutput(CMD_num))
CMD_name = '''snmpwalk -v 2c -c limi@2018  10.200.250.5 enterprises.2011.6.139.13.3.10.1.5 | awk  '{print $4}' | sed 's/"//g' '''

ap_name = subprocess.getoutput(CMD_name)
Name_list = ap_name.split("\n")

for id in range(0,Num):
    CMD = "snmpwalk -v 2c -c limi@2018  10.200.250.5 1.3.6.1.4.1.2011.6.139.13.3.10.1.45.%s | awk '{print $4}'"%id  #AP连接用户数
    Sum = int(subprocess.getoutput(CMD))
    User_list.append(Sum)

data = json.dumps({'APUser':User_list,'APNAME':Name_list})
with open('/var/www/html/echarts/data/data'+'.json','w') as f:
     f.write(data)

1.1.2 echarts 渲染

在此表示 echarts 很强大

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>用户数显示</title>
    <script src="js/jquery-1.12.4.js"></script>
    <script src="js/echarts.min.js"></script>

</head>

<body>
<div id="main" style="width:2400px;height:800px;"></div>

<script>
    var myChart = echarts.init(document.getElementById('main'));
    // 异步加载数据
    $.get('data/data.json').done(function (data) {

        // 填入数据
        myChart.setOption({
            title: {
                text: 'AP用户数连接示例'
            },
            tooltip: {},
            legend: {
                data: ['用户数']
            },
            xAxis: {
                data: data.APNAME
            },
            yAxis: {},
            series: [{
                name: '用户数',
                type: 'bar',
                data: data.APUser
            }]
        });
    });
</script>
</body>
</html>

效果图:

image.png

2. 展示网络设备上下行流量

2.1 首先检索主机列表,找到 hostid:

import requests
import json
import os
url = 'http://192.168.51.202/api_jsonrpc.php'
headers = {'Content-Type': 'application/json-rpc'}
def login():

    post_data = {
	    "jsonrpc":"2.0",
	    "method":"user.login",
	    "params":{
		    "user":"cuijianzhe",
		    "password":"jhzxxb@100"
		    },
		    "id":1
    }

    res = requests.post(url,data=json.dumps(post_data),headers=headers)
    zabbix_res = (json.loads(res.text)).get('result')
    return zabbix_res
def get_data(token):
    post_data = {
        "jsonrpc": "2.0",
        "method": "host.get",
        "params": {
            "output": [
                "hostid",
                "host"
            ],
            "selectInterfaces": [
                "interfaceid",
                "ip"
            ]
        },
        "id": 2,
        "auth": token
    }
    res = requests.post(url, data=json.dumps(post_data), headers=headers)
    traffic_res = json.loads(res.text)
    # print(json.dumps(traffic_res, sort_keys=True, indent=4, separators=(',', ':')))
    results = traffic_res.get('result')
    for i in results:
        print(i)

if __name__ == "__main__":
    auth = login()
    get_data(auth)

2.2 从 zabbix 源获取数据:

import requests
import json
import os
url = 'http://192.168.51.202/api_jsonrpc.php'
headers = {'Content-Type': 'application/json-rpc'}
def login():

    post_data = {
	    "jsonrpc":"2.0",
	    "method":"user.login",
	    "params":{
		    "user":"cuijianzhe",
		    "password":"jhzxxb@100"
		    },
		    "id":1
    }

    res = requests.post(url,data=json.dumps(post_data),headers=headers)
    zabbix_res = (json.loads(res.text)).get('result')
    return zabbix_res
def get_data(token):
    post_data = {
        "jsonrpc": "2.0",
        "method": "item.get",
        "params": {
            "output": "extend",
            "hostids": "10290",
            "search": {
                "key_": "net.if.in"
            },
            "sortfield": "name"
        },
        "auth": token,
        "id": 1
    }

    res = requests.post(url, data=json.dumps(post_data), headers=headers)
    traffic_res = json.loads(res.text)
    # print(json.dumps(traffic_res, sort_keys=True, indent=4, separators=(',', ':')))
    results = traffic_res.get('result')
    #直播间数据整理
    list_room = []
    list_port = []
    list_name = [1, 3, 5, 7, 9, 11, 23, 21, 19, 17, 15, 13, 25, 27, 29, 31, 33, 35, 2, 43, 41, 39, 37, 4, 6, 8, 10, 12,14,16]

    for l in list_name:
        list_port.append('Interface GigabitEthernet0/0/%d(): Bits received' % l)
    # out:  Interface GigabitEthernet0/0/22(): Bits sent
    # in:  Interface GigabitEthernet0/0/1(): Bits received
    for i in range(1, 31):
        list_room.append('LiveRoom%d' %i)
    # sum = 1
    # while sum < 31:
    #     for j in list_port:
    #         sum += 1
    # print('直播间:%s,对应端口:%s'%(sum-1,j))
    port_room = list(zip(list_room, list_port))
    pr_dict = dict(port_room)

    # for pr in port_room:
    #     pr_dict[pr[0]] = pr[1]
    # print(pr_dict)

##循环api返回值和房间端口号,取集合
    # 整合数据
    list_receive = []
    list_name = []
    for k in results:
        for m in pr_dict:
            if k['name'] == pr_dict[m]:
                # print(m,k['lastvalue'])
                traff = (int(k['lastvalue']))/1024   #默认取值为bps,转化为kbps
                list_receive.append(traff)
                list_name.append(m)
    data = json.dumps({'Room': list_name, 'Values': list_receive})
    return data

if __name__ == "__main__":
    auth = login()
    with open('./Liveroom_in' + '.json', 'w') as f:
        f.write(get_data(auth))

图例:

image.png

搭讪 你就破功了,老弟!

记录精彩的坎坷人生,经营属于自己的世界!