pow1.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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(varBind[0]): varBind[1].prettyPrint() for varBind in varBinds}
  63. table.append(row)
  64. return table
  65. @app.route('/')
  66. def index():
  67. # The 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. </style>
  79. </head>
  80. <body>
  81. <h1>SNMP Web Interface</h1>
  82. <!-- SNMP GET Form -->
  83. <h2>SNMP GET</h2>
  84. <input type="text" id="get_ip" placeholder="IP Address">
  85. <input type="text" id="get_community" placeholder="Community" value="public">
  86. <input type="text" id="get_oid" placeholder="OID">
  87. <button onclick="performGet()">Get</button>
  88. <div id="get_result" class="result"></div>
  89. <!-- SNMP SET Form -->
  90. <h2>SNMP SET</h2>
  91. <input type="text" id="set_ip" placeholder="IP Address">
  92. <input type="text" id="set_community" placeholder="Community" value="public">
  93. <input type="text" id="set_oid" placeholder="OID">
  94. <input type="text" id="set_value" placeholder="Value">
  95. <select id="set_type">
  96. <option value="OctetString">OctetString</option>
  97. <option value="Integer">Integer</option>
  98. <option value="IpAddress">IpAddress</option>
  99. </select>
  100. <button onclick="performSet()">Set</button>
  101. <div id="set_result" class="result"></div>
  102. <!-- SNMP TABLE Form -->
  103. <h2>SNMP TABLE</h2>
  104. <input type="text" id="table_ip" placeholder="IP Address">
  105. <input type="text" id="table_community" placeholder="Community" value="public">
  106. <input type="text" id="table_oid" placeholder="Base OID">
  107. <button onclick="performTable()">Get Table</button>
  108. <div id="table_result" class="result"></div>
  109. <script>
  110. function performGet() {
  111. const ip = document.getElementById('get_ip').value;
  112. const community = document.getElementById('get_community').value;
  113. const oid = document.getElementById('get_oid').value;
  114. fetch(`/snmp/get?ip=${ip}&community=${community}&oid=${oid}`)
  115. .then(response => response.json())
  116. .then(data => {
  117. document.getElementById('get_result').textContent = JSON.stringify(data, null, 2);
  118. });
  119. }
  120. function performSet() {
  121. const ip = document.getElementById('set_ip').value;
  122. const community = document.getElementById('set_community').value;
  123. const oid = document.getElementById('set_oid').value;
  124. const value = document.getElementById('set_value').value;
  125. const type = document.getElementById('set_type').value;
  126. fetch(`/snmp/set`, {
  127. method: 'POST',
  128. headers: { 'Content-Type': 'application/json' },
  129. body: JSON.stringify({ ip, community, oid, value, value_type: type })
  130. })
  131. .then(response => response.json())
  132. .then(data => {
  133. document.getElementById('set_result').textContent = JSON.stringify(data, null, 2);
  134. });
  135. }
  136. function performTable() {
  137. const ip = document.getElementById('table_ip').value;
  138. const community = document.getElementById('table_community').value;
  139. const oid = document.getElementById('table_oid').value;
  140. fetch(`/snmp/table?ip=${ip}&community=${community}&base_oid=${oid}`)
  141. .then(response => response.json())
  142. .then(data => {
  143. document.getElementById('table_result').textContent = JSON.stringify(data, null, 2);
  144. });
  145. }
  146. </script>
  147. </body>
  148. </html>
  149. """)
  150. @app.route('/snmp/get', methods=['GET'])
  151. def api_snmp_get():
  152. ip = request.args.get('ip')
  153. community = request.args.get('community', 'public')
  154. oid = request.args.get('oid')
  155. if not ip or not oid:
  156. return {"error": "Missing required parameters: ip, oid"}, 400
  157. result = snmp_get(ip, community, oid)
  158. return jsonify(result)
  159. @app.route('/snmp/set', methods=['POST'])
  160. def api_snmp_set():
  161. data = request.json
  162. ip = data.get('ip')
  163. community = data.get('community', 'public')
  164. oid = data.get('oid')
  165. value = data.get('value')
  166. value_type = data.get('value_type', 'OctetString')
  167. if not ip or not oid or value is None:
  168. return {"error": "Missing required parameters: ip, oid, value"}, 400
  169. result = snmp_set(ip, community, oid, value, value_type)
  170. return jsonify(result)
  171. @app.route('/snmp/table', methods=['GET'])
  172. def api_snmp_get_table():
  173. ip = request.args.get('ip')
  174. community = request.args.get('community', 'public')
  175. base_oid = request.args.get('base_oid')
  176. if not ip or not base_oid:
  177. return {"error": "Missing required parameters: ip, base_oid"}, 400
  178. result = snmp_get_table(ip, community, base_oid)
  179. return jsonify(result)
  180. if __name__ == '__main__':
  181. app.run(host='0.0.0.0', port=5032)