| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234 |
- 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("""
- <!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; }
- table { width: 100%; border-collapse: collapse; margin-top: 20px; }
- table, th, td { border: 1px solid #ddd; padding: 8px; }
- th { background-color: #f2f2f2; }
- </style>
- </head>
- <body>
- <h1>SNMP Web Interface</h1>
-
- <!-- SNMP TABLE Form -->
- <h2>SNMP TABLE</h2>
- <input type="text" id="table_ip" placeholder="apc-pdu-01.dezendorf.net">
- <input type="text" id="table_community" placeholder="Community" value="t33cHm">
- <input type="text" id="table_oid" placeholder="Base OID">
- <button onclick="performTable()">Get Table</button>
- <div id="table_result" class="result"></div>
- <script>
- 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 => {
- if (data.error) {
- document.getElementById('table_result').innerHTML = `<div>${data.error}</div>`;
- } else {
- let tableHtml = '<table><thead><tr><th>OID</th><th>Value</th></tr></thead><tbody>';
- data.forEach(row => {
- Object.entries(row).forEach(([oid, value]) => {
- tableHtml += `<tr><td>${oid}</td><td contenteditable="true" onblur="updateCell('${ip}', '${community}', '${oid}', this.innerText)">${value}</td></tr>`;
- });
- });
- tableHtml += '</tbody></table>';
- document.getElementById('table_result').innerHTML = tableHtml;
- }
- });
- }
- function updateCell(ip, community, oid, value) {
- fetch(`/snmp/set`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ ip, community, oid, value, value_type: "OctetString" })
- })
- .then(response => response.json())
- .then(data => {
- if (data.error) {
- alert("Failed to update: " + data.error);
- } else {
- alert("Update successful!");
- }
- });
- }
- </script>
- </body>
- </html>
- """)
- @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)
- @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)
- class PDU:
- def __init__(self, hostName, portNumber, community):
- self.hostName = hostName
- self.community = "t33cHm3"
- self.port = 161
- def getHost(self):
- return self.hostName
- def setHost(self, hostname):
- self.hostName = hostName
- return self.hostName
- class PDUPort:
- def __init__(self, pdu, portNumber, portName, powerState):
- def setPortName(self, portName):
- self.portName = portName
- try:
- snmp_set(self, self.community, <oid>, self.name, 'string')
- else:
- return False
- return True
- def setPDU(self, pdu):
- self.pdu = pdu
- return pdu.hostname
- def setPowerState(self, powerState):
- self.powerState = powerState
- return self.powerState
- def set
- def getPortName(self):
- return self.portName
- def getPortNumber(self):
- return self.portNumber
- def getPowerState(self):
- return self.powerState
- if __name__ == '__main__':
- # app.run(host='0.0.0.0', port=5032
- table = snmp_get_table("apc-pdu-01.dezendorf.net", "t33cHm3", "1.3.6.1.4.1.318.1.1.4.4.2.1")
- for k in table:
- k1 = k.replace("1.3.6.1.4.1.318.1.1.4.4.2.1.", "")
- print(f"{k1}: {table[k]}")
|