kongou-ae
7/29/2014 - 12:55 PM

onePK-traffic-graphite.py

onePK-traffic-graphite.py

#/usr/bin/env python
# -*- coding: utf-8 -*-

import onep
import time
import subprocess
import datetime
from onep.element import *
from onep.interfaces import *
from subprocess import Popen, PIPE

host = 'your.network.host'
ca_certs = '/path/to/your/ca.pem'
user_name = 'user_nama'
password = 'password'
target_interface = 'interface_number'

def get_traffic():
    network_element = NetworkElement(host,'onepk-traffic')
    session_config = SessionConfig(SessionConfig.SessionTransportMode.TLS)
    session_config.ca_certs = ca_certs

    try:
        session_handle = network_element.connect(user_name, password, session_config)

        interface = network_element.get_interface_by_name(target_interface)
        int_stats = interface.get_statistics()
        in_persec = int_stats.get_param(InterfaceStatistics.InterfaceStatisticsParameter.ONEP_IF_STAT_RX_BYTES_PER_SEC)
        out_persec = int_stats.get_param(InterfaceStatistics.InterfaceStatisticsParameter.ONEP_IF_STAT_TX_BYTES_PER_SEC)

        network_element.disconnect()

    except Exception as e:
        print( 'type:' + str(type(e)))
        print( 'args:' + str(e.args))
        print( 'message:' + e.message)
        network_element.disconnect()

    return in_persec,out_persec

if __name__ == '__main__':

    traffic = get_traffic()
    in_persec = traffic[0]
    out_persec = traffic[1]

    now = datetime.datetime.now()
    now = int(time.mktime(now.timetuple()))

    inbound_nc = "echo " + host + ".traffic." + target_interface + ".inbound " + str(in_persec) + " " + str(now) + " | nc 127.0.0.1 2003"
    outbound_nc = "echo " + host + ".traffic." + target_interface + ".outbound " + str(out_persec) + " " + str(now) + " | nc 127.0.0.1 2003"

    subprocess.call(inbound_nc, shell=True)
    subprocess.call(outbound_nc, shell=True)