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, 'String': String, '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 = [] tableBetter = {} 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: for varBind in varBinds: tableBetter[str(varBind[0])] = str(varBind[1].prettyPrint()) return tableBetter @app.route('/') def index(): # Main HTML page with a simple web UI return render_template_string("""