Julien Mabire
Julien Mabire

Reputation: 1

Problem with integrating SNMP into a Flask application with pysnmp version 7.1.16: "Please call .create() to construct UdpTransportTarget object"

I am trying to integrate SNMP requests into a Flask application using pysnmp version 7.1.16. Despite correctly using .create() when initializing the UdpTransportTarget object, I am still encountering the error: Please call .create() to construct UdpTransportTarget object. I have tried different approaches, including adjusting arguments, but the issue persists. The error seems to be linked to how the transport target is being created or initialized.

Here is my code flask :

 from flask import Flask, render_template
 from pysnmp.hlapi.asyncio import *
 import logging
 import asyncio

 logging.basicConfig(level=logging.DEBUG)

 app = Flask(__name__)

 # Liste des IPs des imprimantes
 ips = [
     "10.140.212.100", "10.140.212.102", "10.140.212.103",
     "10.140.212.106", "10.140.212.107", "10.140.212.108",
     "10.140.212.110", "10.140.212.111", "10.140.212.112", "10.140.212.114"
 ]

 # Fonction SNMP asynchrone
 async def get_snmp_data(ip, oid, community='public'):
     try:
         logging.debug(f"Interrogation SNMP sur {ip} avec OID {oid}")

         # Création de l'itérateur SNMP avec l'API asyncio
         iterator = get_cmd(
             SnmpEngine(),
             CommunityData(community),
             UdpTransportTarget((ip, 161)).create(),
             ContextData(),
             ObjectType(ObjectIdentity(oid))
         )

         # Attendre et récupérer les résultats
         errorIndication, errorStatus, errorIndex, varBinds = await          asyncio.wait_for(iterator.__anext__(), timeout=10)

         if errorIndication:
             return f"Erreur SNMP : {errorIndication}"
         if errorStatus:
             return f"Erreur SNMP : {errorStatus.prettyPrint()}"
         return varBinds[0].prettyPrint()
     except Exception as e:
         return f"Une erreur est survenue : {str(e)}"

 # Route d'accueil
 @app.route('/')
 def index():
     return render_template("impht.html", ips=ips)

 # Route pour exécuter le script SNMP
 @app.route('/execute/<ip>', methods=['POST'])
 async def execute_script(ip):
     oids = {
         'nom': '.1.3.6.1.2.1.1.5.0',   # OID pour le nom
         'description': '.1.3.6.1.2.1.1.1.0',  # OID pour la description
     }

     # Lancer les appels SNMP de manière asynchrone
     results = {}
     for key, oid in oids.items():
         results[key] = await get_snmp_data(ip, oid)

     result_html = "<br>".join([f"{key}: {value}" for key, value in results.items()])
     return f"Informations pour l'imprimante {ip} :<br><pre>{result_html}</pre>"

 if __name__ == "__main__":
     app.run(debug=True)`

here is my code html :

`<!DOCTYPE html>
 <html lang="fr">
 <head>
     <meta charset="UTF-8">
     <title>Info des Imprimantes</title>
     <link rel="stylesheet" href="{{ url_for('static', filename='css/imp.css') }}">
 </head>
 <body>
     {% for ip in ips %}
     <div class="container">
         <h1>Info de l'imprimante {{ ip }}</h1>
          <form method="post" action="{{ url_for('execute_script', ip=ip) }}">
             <button type="submit">Exécuter</button>
         </form>
     </div>
     {% endfor %}
 </body>
 </html>`

I tried using the .create() method with the UdpTransportTarget object, but it still didn't work as expected. I was expecting the SNMP query to execute correctly and return the desired information from the printer, but instead, I received an error message stating Please call .create() to construct UdpTransportTarget object even after calling .create().

Upvotes: -1

Views: 79

Answers (0)

Related Questions