功能

访问远程交换机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. (扫码二维码不显示)php微信扫码支付sdk不能用了

    解决方案: img标签中src 该为qrcode.php的绝对路径,如: 备注:微信端这个生成二维码的路径老是改,之前是http://paysdk.weixin.qq.com/example/qrco ...

  2. Python 爬虫笔记

    urllib python3 与 python2 的urllib很不一样,之前urllib2的方法基本上都变成了python3里的urllib.request模块中 import urllib.req ...

  3. 文件上传Django

    当Django在处理文件上传的时候,文件数据被保存在request.FILES FILES中的每个键为<input type="file" name="" ...

  4. PAT天梯赛L2-007 家庭房产

    题目链接:点击打开链接 给定每个人的家庭成员和其自己名下的房产,请你统计出每个家庭的人口数.人均房产面积及房产套数. 输入格式: 输入第一行给出一个正整数N(<=1000),随后N行,每行按下列 ...

  5. Linux下iptables总结

    linux下防火墙iptables 工作于网络或主机边缘,对进出本网络或本主机的网络报文安装事先设定好的匹配规则进行检查,对能够被规则所匹配的报文按照规则定义的处理机制进行处理的组件 通常情况下ipt ...

  6. KMP 串的模式匹配 (25 分)

    给定两个由英文字母组成的字符串 String 和 Pattern,要求找到 Pattern 在 String 中第一次出现的位置,并将此位置后的 String 的子串输出.如果找不到,则输出“Not ...

  7. Silverlight 登陆界面

    美术水平有限,不喜勿喷. 界面代码,效果如下图 <UserControl x:Class="ElecDemoTelerikSL.Login" xmlns="http ...

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

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

  9. LeetCode 128 Longest Consecutive Sequence 一个无序整数数组中找到最长连续序列

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence.Fo ...

  10. Java文件与io——复制文件和转换流

    字节流与字符流的区别 在所有的流操作里,字节永远是最基础的.任何基于字节的操作都是正确的.无论是文本文件还是二进制的文件. 如果确认流里面只有可打印的字符,包括英文的和各种国家的文字,也包括中文,那么 ...