功能

访问远程交换机snmp数据,写入本地influxdb数据库

#!/usr/bin/env python
# -*- encoding: utf-8 -*- import os, yaml, time
import cPickle as pickle
import threading
import Queue from pysnmp.entity.rfc3413.oneliner import cmdgen
from influxdb import InfluxDBClient def get_config_info(file):
with open(file, 'r') as f:
content = yaml.load(f) return content['web'], content['interval'], content['switch'] def mib_vars(mib, oids, indices = None):
if indices is None:
return [cmdgen.MibVariable(mib, x) for x in oids.split()]
else:
return [cmdgen.MibVariable(mib, x, indices) for x in oids.split()] def int_str(x):
try:
return int(x)
except ValueError:
return str(x) def get_traffic_snmp(ip, community, interface, *args):
count = 0
while count < 2:
try:
errorIndication, errorStatus, errorIndex, varBindTable = cmdgen.CommandGenerator().nextCmd(
cmdgen.CommunityData(community),
cmdgen.UdpTransportTarget((ip, 161)),
*args, lookupNames = True, lookupValues = True
) for varBindRow in varBindTable:
row = [ int_str(val) for name, val in varBindRow if name]
if row[0] == interface:
return row[1], row[2]
except Exception:
count += 1
continue
return 0, 0 class SwitchTraffic(threading.Thread):
def __init__(self, queue, name, ip, community, interface, interval):
threading.Thread.__init__(self)
self.queue = queue
self.name = name
self.ip = ip
self.community = community
self.interface = interface
self.interval = interval def run(self):
oids = mib_vars('IF-MIB', 'ifName ifHCInOctets ifHCOutOctets')
file = os.path.join('/tmp', 'cache-' + self.ip) while 1:
if os.path.exists(file):
with open(file, 'rb+') as f:
p = pickle.load(f)
time_pre, in_pre, out_pre = (p[0], p[1], p[2]) in_cur, out_cur = get_traffic_snmp(self.ip, self.community, self.interface, *oids)
time_cur = int(time.time())
pickle.dump([time_cur, in_cur, out_cur], f) if in_cur - in_pre != 0:
total = (in_cur * 8 - in_pre * 8)
diff = time_cur - time_pre if time_cur - time_pre != 0 else 0
in_mbit = float(total) / diff / 1000 / 1000
else:
in_mbit = 0 if out_cur - out_pre != 0:
total = (out_cur * 8 - out_pre * 8)
diff = time_cur - time_pre if time_cur - time_pre != 0 else 0
out_mbit = float(total) / diff / 1000 / 1000
else:
out_mbit = 0 self.queue.put( (time_cur, self.name, round(in_mbit, 2), round(out_mbit, 2)) ) else:
with open(file, 'wb') as f:
time_cur = int(time.time())
in_pre, out_pre = get_traffic_snmp(self.ip, self.community, self.interface, *oids)
time_pre = int(time.time())
pickle.dump([time_pre, in_pre, out_pre], f) self.queue.put( (time_cur, self.name, 0, 0) ) time.sleep(self.interval) class TimeSeriesDB(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue def run(self):
while True:
try:
client = InfluxDBClient('localhost', 8086, 'root', 'root', 'dashboard')
timestamp, name, traffic_in, traffic_out = self.queue.get()
data = [
{ 'measurement': 'traffic_in', 'tags': {'host': name}, 'time': timestamp, 'fields': {'value': traffic_in} }, \
{ 'measurement': 'traffic_out', 'tags': {'host': name}, 'time': timestamp, 'fields': {'value': traffic_out} }, \
]
client.write_points(data, time_precision='s')
print name, int(time.time()), traffic_in, traffic_out
except Exception:
continue def main():
queue = Queue.Queue()
file = 'dashboard.yaml'
web, interval, switch = get_config_info(file) for i in switch:
producer = SwitchTraffic(queue, i['name'], i['ip'], i['community'], i['interface'], interval)
producer.start() consumer = TimeSeriesDB(queue)
consumer.start() if __name__ == '__main__':
main()

pysnmp程序的更多相关文章

  1. SNMP学习笔记之Python的netsnmp和pysnmp的性能对比

    0x00 概览 用python获取snmp信息有多个现成的库可以使用,其中比较常用的是netsnmp和pysnmp两个库.网上有较多的关于两个库的例子. 本文重点在于如何并发的获取snmp的数据,即同 ...

  2. JavaScript之父Brendan Eich,Clojure 创建者Rich Hickey,Python创建者Van Rossum等编程大牛对程序员的职业建议

    软件开发是现时很火的职业.据美国劳动局发布的一项统计数据显示,从2014年至2024年,美国就业市场对开发人员的需求量将增长17%,而这个增长率比起所有职业的平均需求量高出了7%.很多人年轻人会选择编 ...

  3. 【小程序分享篇 一 】开发了个JAVA小程序, 用于清除内存卡或者U盘里的垃圾文件非常有用

    有一种场景, 手机内存卡空间被用光了,但又不知道哪个文件占用了太大,一个个文件夹去找又太麻烦,所以我开发了个小程序把手机所有文件(包括路径下所有层次子文件夹下的文件)进行一个排序,这样你就可以找出哪个 ...

  4. 微信小程序开发心得

    微信小程序也已出来有一段时间了,最近写了几款微信小程序项目,今天来说说感受. 首先开发一款微信小程序,最主要的就是针对于公司来运营的,因为,在申请appid(微信小程序ID号)时候,需要填写相关的公司 ...

  5. node.js学习(三)简单的node程序&&模块简单使用&&commonJS规范&&深入理解模块原理

    一.一个简单的node程序 1.新建一个txt文件 2.修改后缀 修改之后会弹出这个,点击"是" 3.运行test.js 源文件 使用node.js运行之后的. 如果该路径下没有该 ...

  6. 微信应用号(小程序)开发IDE配置(第一篇)

    2016年9月22日凌晨,微信宣布“小程序”问世,当然只是开始内测了,微信公众平台对200个服务号发送了小程序内测邀请.那么什么是“小程序”呢,来看微信之父怎么说 看完之后,相信大家大概都有些明白了吧 ...

  7. 编写高质量代码:改善Java程序的151个建议(第5章:数组和集合___建议75~78)

    建议75:集合中的元素必须做到compareTo和equals同步 实现了Comparable接口的元素就可以排序,compareTo方法是Comparable接口要求必须实现的,它与equals方法 ...

  8. 【探索】在 JavaScript 中使用 C 程序

    JavaScript 是个灵活的脚本语言,能方便的处理业务逻辑.当需要传输通信时,我们大多选择 JSON 或 XML 格式. 但在数据长度非常苛刻的情况下,文本协议的效率就非常低了,这时不得不使用二进 ...

  9. 通过Jexus 部署 dotnetcore版本MusicStore 示例程序

    ASPNET Music Store application 是一个展示最新的.NET 平台(包括.NET Core/Mono等)上使用MVC 和Entity Framework的示例程序,本文将展示 ...

随机推荐

  1. BerkeleyDB原理及其对应API

    BerkeleyDB(简称为BDB)是一种以key-value为结构的嵌入式数据库引擎: 嵌入式:bdb提供了一系列应用程序接口(API),调用这些接口很简单,应用程序和bdb所提供的库一起编译/链接 ...

  2. 工作随记——弹出QQ联系方式

    <a target="_blank" href="http://wpa.qq.com/msgrd?v=1&uin=QQ号码&site=qq& ...

  3. .net core 深入了解配置文件加载过程

    前言     配置文件中程序运行中,担当着不可或缺的角色:通常情况下,使用 visual studio 进行创建项目过程中,项目配置文件会自动生成在项目根目录下,如 appsettings.json, ...

  4. qemu-nbd使用教程

    服务端 服务器环境 已经安装过qemu-img的32位ubuntu ubuntu@ubuntu-virtual-machine:~/laboratory$ uname -a Linux ubuntu- ...

  5. 中山纪念中学20170310洗衣服(贪心,优先队列升序【pair】)

    #include<bits/stdc++.h>using namespace std;typedef pair<long long,int>clot;priority_queu ...

  6. poj 1741 Tree(树的点分治)

    poj 1741 Tree(树的点分治) 给出一个n个结点的树和一个整数k,问有多少个距离不超过k的点对. 首先对于一个树中的点对,要么经过根结点,要么不经过.所以我们可以把经过根节点的符合点对统计出 ...

  7. KSOAP2使用注意点汇总

    注意返回类型,如果是XML格式,使用 1:SoapObject soapObject = (SoapObject) envelope.getResponse(); 2:SoapObject resul ...

  8. Eclipse下tomcat输出路径配置

    在Eclipse下配置server为Tomcat(一般为Tomcat 6.X),双击server面板中的Tomcat v6.0 Server,出现的Server Locations配置有三个选项: 1 ...

  9. Java中的生产者和消费者实例(多线程 等待唤醒机制)

    1.什么是等待唤醒 我们实现的效果 创建生产者和消费者  对服装进行生产  和售卖 实现生产一个就消费一个 来观察线程的各种状态 下面是用到的方法: wait()方法:让一个线程进行等待 另外一个线程 ...

  10. props简单小栗子

    props简单小栗子 可以直接copy查看结果 <!DOCTYPE html> <html lang="en"> <head> <meta ...