功能

访问远程交换机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. Entity Framework Code-First(9.5):DataAnnotations - MaxLength Attribute

    DataAnnotations - MaxLength Attribute: MaxLength attribute can be applied to a string or array type ...

  2. DMA缓冲区乒乓操作的处理

    http://www.51hei.com/bbs/dpj-141761-1.html https://blog.csdn.net/sunnydreamrain/article/details/8288 ...

  3. DESede/CBC/PKCS5Padding

    Java.security.NoSuchAlgorithmException: Cannot find any provider supporting DESede/CBC/PKCS5Padding ...

  4. Permutations and Permutations II

    Permutations 问题:给定一个无重复元素的数组,输出其中元素可能的所有排列 示例: 输入:[2,3,4] 输出:[ [2,3,4], [2,4,3], [3,2,4], [3,4,2], [ ...

  5. 洛谷P1098 字符串的展开

    P1098 字符串的展开 题目描述 在初赛普及组的“阅读程序写结果”的问题中,我们曾给出一个字符串展开的例子:如果在输入的字符串中,含有类似于“d-h”或者“4-8”的字串,我们就把它当作一种简写,输 ...

  6. POJ2388-Who's in the Middle

    题目链接:点击打开链接 Who's in the Middle Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 45683   ...

  7. asddf

    https://docs.saltstack.com/en/getstarted/fundamentals/index.html https://pypi.org/simple/cherrypy/ 安 ...

  8. Ubuntu16.04安装Nvidia显卡驱动+Cuda8.0+Cudnn6.0

    一.安装Nvidia显卡驱动(gtx1050ti) 参考链接:Ubuntu16.04.2 LTS 64bit系统装机记录中的显卡驱动安装部分. 二.安装Cuda8.0 1.确定自己的系统信息,以Ubu ...

  9. 024 Swap Nodes in Pairs 交换相邻结点

    给定一个链表,对每两个相邻的结点作交换并返回头节点.例如:给定 1->2->3->4,你应该返回 2->1->4->3.你的算法应该只使用额外的常数空间.不要修改列 ...

  10. 005 Longest Palindromic Substring 最长回文子串

    Given a string s, find the longest palindromic substring in s. You may assume that the maximum lengt ...