| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214 |
- from flask import Flask, request, jsonify, render_template_string
- from pysnmp.hlapi import *
- app = Flask(__name__)
- def snmp_get(ip, community, oid):
- iterator = getCmd(
- SnmpEngine(),
- CommunityData(community, mpModel=1), # mpModel=1 for SNMP v2c
- UdpTransportTarget((ip, 161)),
- ContextData(),
- ObjectType(ObjectIdentity(oid))
- )
- errorIndication, errorStatus, errorIndex, varBinds = next(iterator)
- if errorIndication:
- return {"error": str(errorIndication)}, 500
- elif errorStatus:
- return {"error": str(errorStatus.prettyPrint())}, 500
- else:
- for varBind in varBinds:
- return {"value": varBind.prettyPrint().split("=")[-1].strip()}
- def snmp_set(ip, community, oid, value, value_type):
- type_map = {
- 'Integer': Integer,
- 'OctetString': OctetString,
- 'IpAddress': IpAddress,
- 'Counter32': Counter32,
- 'Gauge32': Gauge32,
- 'TimeTicks': TimeTicks
- }
-
- if value_type not in type_map:
- return {"error": f"Unsupported value type: {value_type}"}, 400
- data_type = type_map[value_type]
-
- iterator = setCmd(
- SnmpEngine(),
- CommunityData(community, mpModel=1),
- UdpTransportTarget((ip, 161)),
- ContextData(),
- ObjectType(ObjectIdentity(oid), data_type(value))
- )
- errorIndication, errorStatus, errorIndex, varBinds = next(iterator)
- if errorIndication:
- return {"error": str(errorIndication)}, 500
- elif errorStatus:
- return {"error": str(errorStatus.prettyPrint())}, 500
- else:
- return {"status": "Set request successful"}
- def snmp_get_table(ip, community, base_oid):
- table = []
- iterator = nextCmd(
- SnmpEngine(),
- CommunityData(community, mpModel=1),
- UdpTransportTarget((ip, 161)),
- ContextData(),
- ObjectType(ObjectIdentity(base_oid)),
- lexicographicMode=False
- )
- for errorIndication, errorStatus, errorIndex, varBinds in iterator:
- if errorIndication:
- return {"error": str(errorIndication)}, 500
- elif errorStatus:
- return {"error": str(errorStatus.prettyPrint())}, 500
- else:
- row = {str(varBind[0]): varBind[1].prettyPrint() for varBind in varBinds}
- table.append(row)
- return table
- @app.route('/')
- def index():
- # The main HTML page with a simple web UI
- return render_template_string("""
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>SNMP Web Interface</title>
- <style>
- body { font-family: Arial, sans-serif; margin: 20px; }
- input, select, button { margin: 5px; padding: 5px; }
- .result { margin-top: 15px; padding: 10px; background: #f9f9f9; border: 1px solid #ddd; }
- </style>
- </head>
- <body>
- <h1>SNMP Web Interface</h1>
-
- <!-- SNMP GET Form -->
- <h2>SNMP GET</h2>
- <input type="text" id="get_ip" placeholder="IP Address">
- <input type="text" id="get_community" placeholder="Community" value="public">
- <input type="text" id="get_oid" placeholder="OID">
- <button onclick="performGet()">Get</button>
- <div id="get_result" class="result"></div>
-
- <!-- SNMP SET Form -->
- <h2>SNMP SET</h2>
- <input type="text" id="set_ip" placeholder="IP Address">
- <input type="text" id="set_community" placeholder="Community" value="public">
- <input type="text" id="set_oid" placeholder="OID">
- <input type="text" id="set_value" placeholder="Value">
- <select id="set_type">
- <option value="OctetString">OctetString</option>
- <option value="Integer">Integer</option>
- <option value="IpAddress">IpAddress</option>
- </select>
- <button onclick="performSet()">Set</button>
- <div id="set_result" class="result"></div>
-
- <!-- SNMP TABLE Form -->
- <h2>SNMP TABLE</h2>
- <input type="text" id="table_ip" placeholder="IP Address">
- <input type="text" id="table_community" placeholder="Community" value="public">
- <input type="text" id="table_oid" placeholder="Base OID">
- <button onclick="performTable()">Get Table</button>
- <div id="table_result" class="result"></div>
- <script>
- function performGet() {
- const ip = document.getElementById('get_ip').value;
- const community = document.getElementById('get_community').value;
- const oid = document.getElementById('get_oid').value;
-
- fetch(`/snmp/get?ip=${ip}&community=${community}&oid=${oid}`)
- .then(response => response.json())
- .then(data => {
- document.getElementById('get_result').textContent = JSON.stringify(data, null, 2);
- });
- }
- function performSet() {
- const ip = document.getElementById('set_ip').value;
- const community = document.getElementById('set_community').value;
- const oid = document.getElementById('set_oid').value;
- const value = document.getElementById('set_value').value;
- const type = document.getElementById('set_type').value;
-
- fetch(`/snmp/set`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ ip, community, oid, value, value_type: type })
- })
- .then(response => response.json())
- .then(data => {
- document.getElementById('set_result').textContent = JSON.stringify(data, null, 2);
- });
- }
- function performTable() {
- const ip = document.getElementById('table_ip').value;
- const community = document.getElementById('table_community').value;
- const oid = document.getElementById('table_oid').value;
-
- fetch(`/snmp/table?ip=${ip}&community=${community}&base_oid=${oid}`)
- .then(response => response.json())
- .then(data => {
- document.getElementById('table_result').textContent = JSON.stringify(data, null, 2);
- });
- }
- </script>
- </body>
- </html>
- """)
- @app.route('/snmp/get', methods=['GET'])
- def api_snmp_get():
- ip = request.args.get('ip')
- community = request.args.get('community', 'public')
- oid = request.args.get('oid')
-
- if not ip or not oid:
- return {"error": "Missing required parameters: ip, oid"}, 400
-
- result = snmp_get(ip, community, oid)
- return jsonify(result)
- @app.route('/snmp/set', methods=['POST'])
- def api_snmp_set():
- data = request.json
- ip = data.get('ip')
- community = data.get('community', 'public')
- oid = data.get('oid')
- value = data.get('value')
- value_type = data.get('value_type', 'OctetString')
-
- if not ip or not oid or value is None:
- return {"error": "Missing required parameters: ip, oid, value"}, 400
- result = snmp_set(ip, community, oid, value, value_type)
- return jsonify(result)
- @app.route('/snmp/table', methods=['GET'])
- def api_snmp_get_table():
- ip = request.args.get('ip')
- community = request.args.get('community', 'public')
- base_oid = request.args.get('base_oid')
-
- if not ip or not base_oid:
- return {"error": "Missing required parameters: ip, base_oid"}, 400
- result = snmp_get_table(ip, community, base_oid)
- return jsonify(result)
- if __name__ == '__main__':
- app.run(host='0.0.0.0', port=5032)
|