pow.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. from flask import Flask, request, jsonify, render_template_string
  2. from pysnmp.hlapi import *
  3. app = Flask(__name__)
  4. def snmp_get(ip, community, oid):
  5. iterator = getCmd(
  6. SnmpEngine(),
  7. CommunityData(community, mpModel=1), # mpModel=1 for SNMP v2c
  8. UdpTransportTarget((ip, 161)),
  9. ContextData(),
  10. ObjectType(ObjectIdentity(oid))
  11. )
  12. errorIndication, errorStatus, errorIndex, varBinds = next(iterator)
  13. if errorIndication:
  14. return {"error": str(errorIndication)}, 500
  15. elif errorStatus:
  16. return {"error": str(errorStatus.prettyPrint())}, 500
  17. else:
  18. for varBind in varBinds:
  19. return {"value": varBind.prettyPrint().split("=")[-1].strip()}
  20. def snmp_set(ip, community, oid, value, value_type):
  21. type_map = {
  22. 'Integer': Integer,
  23. 'OctetString': OctetString,
  24. 'IpAddress': IpAddress,
  25. 'Counter32': Counter32,
  26. 'Gauge32': Gauge32,
  27. 'TimeTicks': TimeTicks
  28. }
  29. if value_type not in type_map:
  30. return {"error": f"Unsupported value type: {value_type}"}, 400
  31. data_type = type_map[value_type]
  32. iterator = setCmd(
  33. SnmpEngine(),
  34. CommunityData(community, mpModel=1),
  35. UdpTransportTarget((ip, 161)),
  36. ContextData(),
  37. ObjectType(ObjectIdentity(oid), data_type(value))
  38. )
  39. errorIndication, errorStatus, errorIndex, varBinds = next(iterator)
  40. if errorIndication:
  41. return {"error": str(errorIndication)}, 500
  42. elif errorStatus:
  43. return {"error": str(errorStatus.prettyPrint())}, 500
  44. else:
  45. return {"status": "Set request successful"}
  46. def snmp_get_table(ip, community, base_oid):
  47. table = []
  48. iterator = nextCmd(
  49. SnmpEngine(),
  50. CommunityData(community, mpModel=1),
  51. UdpTransportTarget((ip, 161)),
  52. ContextData(),
  53. ObjectType(ObjectIdentity(base_oid)),
  54. lexicographicMode=False
  55. )
  56. for errorIndication, errorStatus, errorIndex, varBinds in iterator:
  57. if errorIndication:
  58. return {"error": str(errorIndication)}, 500
  59. elif errorStatus:
  60. return {"error": str(errorStatus.prettyPrint())}, 500
  61. else:
  62. row = {str(str(varBind[0]).split('.')[-2], str(varBind[0]).split('.')[-1]): varBind[1].prettyPrint() for varBind in varBinds}
  63. table.append(row)
  64. return table
  65. @app.route('/')
  66. def index():
  67. # Main HTML page with a simple web UI
  68. return render_template_string("""
  69. <!DOCTYPE html>
  70. <html lang="en">
  71. <head>
  72. <meta charset="UTF-8">
  73. <title>SNMP Web Interface</title>
  74. <style>
  75. body { font-family: Arial, sans-serif; margin: 20px; }
  76. input, select, button { margin: 5px; padding: 5px; }
  77. .result { margin-top: 15px; padding: 10px; background: #f9f9f9; border: 1px solid #ddd; }
  78. table { width: 100%; border-collapse: collapse; margin-top: 20px; }
  79. table, th, td { border: 1px solid #ddd; padding: 8px; }
  80. th { background-color: #f2f2f2; }
  81. </style>
  82. </head>
  83. <body>
  84. <h1>SNMP Web Interface</h1>
  85. <!-- SNMP TABLE Form -->
  86. <h2>SNMP TABLE</h2>
  87. <input type="text" id="table_ip" placeholder="apc-pdu-01.dezendorf.net" value="apc-pdu-01.dezendorf.net">
  88. <input type="text" id="table_community" placeholder="Community" value="t33cHm">
  89. <input type="text" id="table_oid" placeholder="1.3.6.1.4.1.318.1.1.4.4.2.1" value="1.3.6.1.4.1.318.1.1.4.4.2.1">
  90. <button onclick="performTable()">Get Table</button>
  91. <div id="table_result" class="result"></div>
  92. <script>
  93. function performTable() {
  94. const ip = document.getElementById('table_ip').value;
  95. const community = document.getElementById('table_community').value;
  96. const oid = document.getElementById('table_oid').value;
  97. fetch(`/snmp/table?ip=${ip}&community=${community}&base_oid=${oid}`)
  98. .then(response => response.json())
  99. .then(data => {
  100. if (data.error) {
  101. document.getElementById('table_result').innerHTML = `<div>${data.error}</div>`;
  102. } else {
  103. let tableHtml = '<table><thead><tr><th>OID</th><th>Value</th></tr></thead><tbody>';
  104. data.forEach(row => {
  105. Object.entries(row).forEach(([oid, value]) => {
  106. tableHtml += `<tr><td>${oid}</td><td contenteditable="true" onblur="updateCell('${ip}', '${community}', '${oid}', this.innerText)">${value}</td></tr>`;
  107. });
  108. });
  109. tableHtml += '</tbody></table>';
  110. document.getElementById('table_result').innerHTML = tableHtml;
  111. }
  112. });
  113. }
  114. function updateCell(ip, community, oid, value) {
  115. fetch(`/snmp/set`, {
  116. method: 'POST',
  117. headers: { 'Content-Type': 'application/json' },
  118. body: JSON.stringify({ ip, community, oid, value, value_type: "OctetString" })
  119. })
  120. .then(response => response.json())
  121. .then(data => {
  122. if (data.error) {
  123. alert("Failed to update: " + data.error);
  124. } else {
  125. alert("Update successful!");
  126. }
  127. });
  128. }
  129. </script>
  130. </body>
  131. </html>
  132. """)
  133. @app.route('/snmp/table', methods=['GET'])
  134. def api_snmp_get_table():
  135. ip = request.args.get('ip')
  136. community = request.args.get('community', 'public')
  137. base_oid = request.args.get('base_oid')
  138. if not ip or not base_oid:
  139. return {"error": "Missing required parameters: ip, base_oid"}, 400
  140. result = snmp_get_table(ip, community, base_oid)
  141. return jsonify(result)
  142. @app.route('/snmp/set', methods=['POST'])
  143. def api_snmp_set():
  144. data = request.json
  145. ip = data.get('ip')
  146. community = data.get('community', 'public')
  147. oid = data.get('oid')
  148. value = data.get('value')
  149. value_type = data.get('value_type', 'OctetString')
  150. if not ip or not oid or value is None:
  151. return {"error": "Missing required parameters: ip, oid, value"}, 400
  152. result = snmp_set(ip, community, oid, value, value_type)
  153. return jsonify(result)
  154. if __name__ == '__main__':
  155. app.run(host='0.0.0.0', port=5032
  156. )