1 Star 0 Fork 0

邓聪聪/traffic

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
poller.py 3.28 KB
一键复制 编辑 原始数据 按行查看 历史
邓聪聪 提交于 2022-07-11 13:40 . 711
# encoding: utf-8
from __future__ import unicode_literals
import os
import sys
from datetime import datetime
import django
import snmpclient
from django.utils import timezone, six
APP_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(APP_DIR)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'traffic.settings')
django.setup()
from core.models import Host, TrafficLog, Collection
def gettraffic():
# now = timezone.now()
now = datetime.strptime(timezone.now().strftime('%Y-%m-%d %H:%M:00'), '%Y-%m-%d %H:%M:%S')
hosts = Host.objects.filter(is_active=True)
for host in hosts:
collect = Collection()
collect.date = now
collect.host = host
try:
client = snmpclient.SnmpClient(host.hostname, host.snmp_port, [
snmpclient.cmdgen.CommunityData('snmpuser', host.snmp_community, snmpclient.V2C)])
ports = host.ports.filter(is_active=True)
for port in ports:
try:
traffic_in = client.get('IF-MIB::ifHCInOctets.%s' % port.oid)
traffic_out = client.get('IF-MIB::ifHCOutOctets.%s' % port.oid)
traffic_in = int(traffic_in)
traffic_out = int(traffic_out)
prev = port.traffic_logs.order_by('-date').first()
if prev is not None:
seconds = (now - prev.date).total_seconds() # + (now - prev.date).days * 86400
in_bits = (traffic_in - prev.traffic_in) / seconds * 8
out_bits = (traffic_out - prev.traffic_out) / seconds * 8
else:
in_bits = 0
out_bits = 0
trafficlog = TrafficLog()
trafficlog.port = port
trafficlog.date = now
trafficlog.traffic_in = traffic_in
trafficlog.traffic_out = traffic_out
trafficlog.in_bits = in_bits
trafficlog.out_bits = out_bits
if in_bits < 0 or out_bits < 0 or (port.name.find('Trunk') < 0 and (in_bits > 10737418240 or out_bits > 10737418240)):
trafficlog.isvalid = False
trafficlog.save()
# print('%020s %020s %015s %015s' % (host.description, port.description, traffic_in, traffic_out))
except Exception as e:
if six.PY2:
err_msg = e.message
else:
err_msg = e
print('%020s %020s Error: %s' % (host.description, port.description, err_msg))
if host.state == '1':
host.state = '0'
host.changed = now
host.save()
collect.is_active = True
except Exception as e:
if six.PY2:
err_msg = e.message
else:
err_msg = e
collect.is_active = False
collect.message = err_msg
if host.state == '0':
host.state = '1'
host.changed = now
host.save()
print('%020s Error: %s' % (host.description, err_msg))
collect.save()
if __name__ == '__main__':
gettraffic()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/deng_chung_chun/traffic.git
[email protected]:deng_chung_chun/traffic.git
deng_chung_chun
traffic
traffic
master

搜索帮助