snmp_pdu.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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. 'String': String,
  28. 'TimeTicks': TimeTicks
  29. }
  30. if value_type not in type_map:
  31. return {"error": f"Unsupported value type: {value_type}"}, 400
  32. data_type = type_map[value_type]
  33. iterator = setCmd(
  34. SnmpEngine(),
  35. CommunityData(community, mpModel=1),
  36. UdpTransportTarget((ip, 161)),
  37. ContextData(),
  38. ObjectType(ObjectIdentity(oid), data_type(value))
  39. )
  40. errorIndication, errorStatus, errorIndex, varBinds = next(iterator)
  41. if errorIndication:
  42. return {"error": str(errorIndication)}, 500
  43. elif errorStatus:
  44. return {"error": str(errorStatus.prettyPrint())}, 500
  45. else:
  46. return {"status": "Set request successful"}
  47. def snmp_get_table(ip, community, base_oid):
  48. table = []
  49. tableBetter = {}
  50. iterator = nextCmd(
  51. SnmpEngine(),
  52. CommunityData(community, mpModel=1),
  53. UdpTransportTarget((ip, 161)),
  54. ContextData(),
  55. ObjectType(ObjectIdentity(base_oid)),
  56. lexicographicMode=False
  57. )
  58. for errorIndication, errorStatus, errorIndex, varBinds in iterator:
  59. if errorIndication:
  60. return {"error": str(errorIndication)}, 500
  61. elif errorStatus:
  62. return {"error": str(errorStatus.prettyPrint())}, 500
  63. else:
  64. for varBind in varBinds:
  65. tableBetter[str(varBind[0])] = str(varBind[1].prettyPrint())
  66. return tableBetter
  67. @app.route('/')
  68. def index():
  69. # Main HTML page with a simple web UI
  70. return render_template_string("""
  71. <!DOCTYPE html>
  72. <html lang="en">
  73. <head>
  74. <meta charset="UTF-8">
  75. <title>SNMP Web Interface</title>
  76. <style>
  77. body { font-family: Arial, sans-serif; margin: 20px; }
  78. input, select, button { margin: 5px; padding: 5px; }
  79. .result { margin-top: 15px; padding: 10px; background: #f9f9f9; border: 1px solid #ddd; }
  80. table { width: 100%; border-collapse: collapse; margin-top: 20px; }
  81. table, th, td { border: 1px solid #ddd; padding: 8px; }
  82. th { background-color: #f2f2f2; }
  83. </style>
  84. </head>
  85. <body>
  86. <h1>SNMP Web Interface</h1>
  87. <!-- SNMP TABLE Form -->
  88. <h2>SNMP TABLE</h2>
  89. <input type="text" id="table_ip" placeholder="apc-pdu-01.dezendorf.net">
  90. <input type="text" id="table_community" placeholder="Community" value="t33cHm">
  91. <input type="text" id="table_oid" placeholder="Base OID">
  92. <button onclick="performTable()">Get Table</button>
  93. <div id="table_result" class="result"></div>
  94. <script>
  95. function performTable() {
  96. const ip = document.getElementById('table_ip').value;
  97. const community = document.getElementById('table_community').value;
  98. const oid = document.getElementById('table_oid').value;
  99. fetch(`/snmp/table?ip=${ip}&community=${community}&base_oid=${oid}`)
  100. .then(response => response.json())
  101. .then(data => {
  102. if (data.error) {
  103. document.getElementById('table_result').innerHTML = `<div>${data.error}</div>`;
  104. } else {
  105. let tableHtml = '<table><thead><tr><th>OID</th><th>Value</th></tr></thead><tbody>';
  106. data.forEach(row => {
  107. Object.entries(row).forEach(([oid, value]) => {
  108. tableHtml += `<tr><td>${oid}</td><td contenteditable="true" onblur="updateCell('${ip}', '${community}', '${oid}', this.innerText)">${value}</td></tr>`;
  109. });
  110. });
  111. tableHtml += '</tbody></table>';
  112. document.getElementById('table_result').innerHTML = tableHtml;
  113. }
  114. });
  115. }
  116. function updateCell(ip, community, oid, value) {
  117. fetch(`/snmp/set`, {
  118. method: 'POST',
  119. headers: { 'Content-Type': 'application/json' },
  120. body: JSON.stringify({ ip, community, oid, value, value_type: "OctetString" })
  121. })
  122. .then(response => response.json())
  123. .then(data => {
  124. if (data.error) {
  125. alert("Failed to update: " + data.error);
  126. } else {
  127. alert("Update successful!");
  128. }
  129. });
  130. }
  131. </script>
  132. </body>
  133. </html>
  134. """)
  135. @app.route('/snmp/table', methods=['GET'])
  136. def api_snmp_get_table():
  137. ip = request.args.get('ip')
  138. community = request.args.get('community', 'public')
  139. base_oid = request.args.get('base_oid')
  140. if not ip or not base_oid:
  141. return {"error": "Missing required parameters: ip, base_oid"}, 400
  142. result = snmp_get_table(ip, community, base_oid)
  143. return jsonify(result)
  144. @app.route('/snmp/set', methods=['POST'])
  145. def api_snmp_set():
  146. data = request.json
  147. ip = data.get('ip')
  148. community = data.get('community', 'public')
  149. oid = data.get('oid')
  150. value = data.get('value')
  151. value_type = data.get('value_type', 'OctetString')
  152. if not ip or not oid or value is None:
  153. return {"error": "Missing required parameters: ip, oid, value"}, 400
  154. result = snmp_set(ip, community, oid, value, value_type)
  155. return jsonify(result)
  156. class PDU:
  157. def __init__(self, hostName, portNumber, community):
  158. self.hostName = hostName
  159. self.community = "t33cHm3"
  160. self.port = 161
  161. def getHost(self):
  162. return self.hostName
  163. def setHost(self, hostname):
  164. self.hostName = hostName
  165. return self.hostName
  166. class PDUPort:
  167. def __init__(self, pdu, portNumber, portName, powerState):
  168. def setPortName(self, portName):
  169. self.portName = portName
  170. try:
  171. snmp_set(self, self.community, <oid>, self.name, 'string')
  172. else:
  173. return False
  174. return True
  175. def setPDU(self, pdu):
  176. self.pdu = pdu
  177. return pdu.hostname
  178. def setPowerState(self, powerState):
  179. self.powerState = powerState
  180. return self.powerState
  181. def set
  182. def getPortName(self):
  183. return self.portName
  184. def getPortNumber(self):
  185. return self.portNumber
  186. def getPowerState(self):
  187. return self.powerState
  188. if __name__ == '__main__':
  189. # app.run(host='0.0.0.0', port=5032
  190. table = snmp_get_table("apc-pdu-01.dezendorf.net", "t33cHm3", "1.3.6.1.4.1.318.1.1.4.4.2.1")
  191. for k in table:
  192. k1 = k.replace("1.3.6.1.4.1.318.1.1.4.4.2.1.", "")
  193. print(f"{k1}: {table[k]}")