Skip to content
This repository was archived by the owner on Dec 17, 2021. It is now read-only.

Commit a90ad8f

Browse files
committed
feat: add mib translator in mib server
1 parent f201cbc commit a90ad8f

File tree

10,668 files changed

+2654683
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

10,668 files changed

+2654683
-0
lines changed

config.yaml

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
snmp:
2+
communities:
3+
v1:
4+
- public
5+
- "my-area"
6+
mibs:
7+
url:
8+
- "file:///usr/share/snmp/mibs"
9+
# *TODO*: Replace below URL with MIB Server's URL returned during service discovery.
10+
- "http://mibs.thola.io/pysnmp/@mib@"
11+
# dir: "/work/mibs"
12+
dir: "/Users/yling/snmp-project/splunk-connect-for-snmp-mib-server/mibs/pysnmp"
13+
# dir: "http://mibs.thola.io/pysnmp/"
14+
load_list: "lookups/mibs_list.csv"
15+
mongo:
16+
oid:
17+
host: "localhost"
18+
port: 27017
19+
database: "snmp_traps"
20+
collection: "oids"
21+
mib:
22+
host: "localhost"
23+
port: 27017
24+
database: "files"
25+
collection: "mib_files"

flask_server/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import logging.config
2+
3+
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s | %(name)s | %(levelname)s | %(message)s')

flask_server/app.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
from flask import Flask, request, abort, jsonify, send_from_directory
2+
from flask_autoindex import AutoIndex
3+
import os
4+
import yaml
5+
import sys
6+
sys.path.append('../')
7+
from flask_server.mongo import MibsRepository, OidsRepository
8+
from flask_server.translator import Translator
9+
10+
11+
print(os.path.join(os.getcwd(), "..", "mibs"))
12+
ppath = os.path.join(os.getcwd(), "..", "mibs")
13+
14+
15+
# Read config file
16+
config_file = os.path.join(os.getcwd(), "..", "config.yaml")
17+
with open(config_file, "r") as yamlfile:
18+
server_config = yaml.load(yamlfile, Loader=yaml.FullLoader)
19+
20+
#Init Translator
21+
snmp_translator = Translator(server_config)
22+
23+
# Init Mongo Client
24+
# mongo_config = {'host': 'localhost', 'port': 27017, 'database': 'files', 'collection': 'mib_files'}
25+
# mib_mongo_config = server_config["mongo"]["mib"]
26+
# oid_mongo_config = server_config["mongo"]["oid"]
27+
28+
# mib_collection = MibsRepository(mib_mongo_config)
29+
# oid_collection = OidsRepository(oid_mongo_config)
30+
# print(f"========={mib_collection} -- {oid_collection}========")
31+
32+
33+
34+
35+
app = Flask(__name__)
36+
# AutoIndex(app, browse_root=ppath)
37+
38+
files_index = AutoIndex(app, ppath, add_url_rules=False)
39+
40+
@app.route('/')
41+
def hello():
42+
return "Hello, This is SNMP MIB server!"
43+
44+
@app.route('/test')
45+
def test():
46+
name = request.args.get('name')
47+
return f"This is {name}'s test"
48+
49+
# Custom indexing
50+
@app.route('/files/')
51+
@app.route('/files/<path:path>')
52+
def autoindex(path='.'):
53+
print(f"path: {path}")
54+
# if '/' in path and '.' in path.split('/')[-1]:
55+
# filename = path.split('/')[-1]
56+
# print(f"filename: {filename}")
57+
# dirpath = os.path.join(ppath, path.split('/')[-2])
58+
# print(f"dirpath: {dirpath}")
59+
# return files_index.render_autoindex(path),send_from_directory(dirpath, filename, as_attachment=True)
60+
return files_index.render_autoindex(path)
61+
62+
# # Search mib files based on oid
63+
# @app.route('/search/mib', methods=['GET'])
64+
# def search_mib_file():
65+
# oid = request.args.get('oid')
66+
# return mib_collection.search_oid(oid)
67+
68+
# Translate oid
69+
@app.route('/translation', methods=['POST'])
70+
def translator():
71+
# how to keep the var_bins as a var_binds object
72+
print(request.json)
73+
var_binds = request.json.get('var_binds')
74+
print(f"type of var_binds: {type(var_binds)}")
75+
print(f"var_binds: {var_binds}")
76+
return snmp_translator.format_trap_event(var_binds)
77+
78+
79+
80+
if __name__ == "__main__":
81+
app.run(host="localhost", port=5000, debug=True)

flask_server/mongo.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
from pymongo import MongoClient
2+
import os
3+
4+
class MibsRepository:
5+
def __init__(self, mongo_config):
6+
"""
7+
Create a collection in mongodb to store mib files
8+
"""
9+
self._client = MongoClient(host=mongo_config['host'], port=mongo_config['port'])
10+
self._mibs = self._client[mongo_config['database']][mongo_config['collection']]
11+
12+
13+
def upload_files(self, mib_files_dir):
14+
"""
15+
Upload mib files from dir to mongo
16+
@param mib_files_dir: the path of the mib files directory
17+
"""
18+
for filename in os.listdir(mib_files_dir):
19+
file_path = mib_files_dir + "/" + filename
20+
# print(file_path)
21+
with open (file_path,'r') as mib_file:
22+
self._mibs.insert_one(dict(
23+
content = mib_file.read(),
24+
filename = filename
25+
))
26+
27+
def search_oid(self, oid):
28+
"""
29+
Search mib file based on oid
30+
@param oid: oid, format: "1, 3, 6, 1, 4, 1, 2356, 11, 0, 0, 10000"
31+
@return mib filename
32+
"""
33+
data = self._mibs.find_one({"content": {"$regex": oid}})
34+
if data:
35+
return data["filename"]
36+
else:
37+
return None
38+
39+
def delete_mib(self, filename):
40+
"""
41+
Delete mib files based on filename
42+
@param filename: mib filename
43+
"""
44+
self._mibs.delete_many({'filename': {"$regex": filename}})
45+
46+
def clear(self):
47+
"""
48+
Clear the collection
49+
"""
50+
self._mibs.remove()
51+
52+
class OidsRepository:
53+
def __init__(self, mongo_config):
54+
self._client = MongoClient(host=mongo_config['host'], port=mongo_config['port'])
55+
self._oids = self._client[mongo_config['database']][mongo_config['collection']]
56+
57+
def contains_oid(self, oid):
58+
return self._oids.find({'oid': oid}).count()
59+
60+
def add_oid(self, oid):
61+
self._oids.insert_one({'oid': oid})
62+
63+
def delete_oid(self, oid):
64+
self._oids.delete_many({'oid': oid})
65+
66+
def clear(self):
67+
self._oids.remove()

0 commit comments

Comments
 (0)