IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

API standards et tierces Java Discussion :

snmpwalk avec snmp4j


Sujet :

API standards et tierces Java

  1. #1
    Membre confirmé
    Inscrit en
    Novembre 2007
    Messages
    81
    Détails du profil
    Informations forums :
    Inscription : Novembre 2007
    Messages : 81
    Par défaut snmpwalk avec snmp4j
    bonjour,

    je veux essayer d'exécuter snmpwalk en utilisant le snmp4j , j'ai arrivé à executer le GET/GETNEXT et le SET en écrivant un programme mais je sais pas comment faire pour le walk.


    merci,

  2. #2
    Membre éprouvé
    Profil pro
    Inscrit en
    Octobre 2003
    Messages
    1 249
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2003
    Messages : 1 249
    Par défaut
    bonjour,

    la commande walk n'existe pas dans le protocole snmp => un walk, c'est simplement un GETNEXT qui tourne en boucle jusqu'à qu'il n'y ai une erreur (ce qui permet de lister les valeurs de toutes les variables)...

  3. #3
    Membre confirmé
    Inscrit en
    Novembre 2007
    Messages
    81
    Détails du profil
    Informations forums :
    Inscription : Novembre 2007
    Messages : 81
    Par défaut
    bonjour,

    en faite, j'ai utiliser le net-snmp à fin de maitriser le snmp , dont j'ai utlisé le snmpwalk qui me permet d'afficher à titre d'exemple les noms de mes bases de données sqlserver.
    je voudrais maintenant avoir les memes résultat mais en écrivant un programme en java en utilisant le snmp4j
    donc que me conseillez vous à faire?

    merci

  4. #4
    Membre confirmé
    Inscrit en
    Novembre 2007
    Messages
    81
    Détails du profil
    Informations forums :
    Inscription : Novembre 2007
    Messages : 81
    Par défaut
    Bonjour
    j'ai arrivé à écrire le programme de snmpwalk.
    voici le code
    #import java.io.IOException;
    import org.snmp4j.CommunityTarget;
    import org.snmp4j.mp.SnmpConstants;
    import org.snmp4j.PDU;
    import org.snmp4j.smi.Address;
    import org.snmp4j.smi.Integer32;
    import org.snmp4j.smi.Null;
    import org.snmp4j.smi.OctetString;
    import org.snmp4j.smi.OID;
    import org.snmp4j.smi.UdpAddress;
    import org.snmp4j.smi.VariableBinding;
    import org.snmp4j.Snmp;
    import org.snmp4j.transport.DefaultUdpTransportMapping;
    import org.snmp4j.TransportMapping;

    public class Snmpwalk
    {

    public static void main(String[] args)
    {
    Address targetAddress = new UdpAddress("127.0.0.1/161");
    OID targetOID = new OID(".1.3.6.1.4.1.311.1.4.1.1.5.1.2");



    PDU requestPDU = new PDU();
    requestPDU.add(new VariableBinding(targetOID));
    requestPDU.setType(PDU.GETNEXT);

    CommunityTarget target = new CommunityTarget();
    target.setCommunity(new OctetString("public"));
    target.setAddress(targetAddress);
    target.setVersion(SnmpConstants.version1);

    try
    {
    TransportMapping transport = new DefaultUdpTransportMapping();
    Snmp snmp = new Snmp(transport);
    transport.listen();

    boolean finished = false;

    while (!finished)
    {
    VariableBinding vb = null;

    PDU responsePDU = snmp.sendPDU(requestPDU, target);
    if (responsePDU != null)
    {
    vb = responsePDU.get(0);
    }

    if (responsePDU == null)
    {
    System.out.println("responsePDU == null");
    finished = true;
    }
    else if (responsePDU.getErrorStatus() != 0)
    {
    System.out.println("responsePDU.getErrorStatus() != 0");
    System.out.println(responsePDU.getErrorStatusText());
    finished = true;
    }
    else if (vb.getOid() == null)
    {
    System.out.println("vb.getOid() == null");
    finished = true;
    }
    else if (vb.getOid().size() < targetOID.size())
    {
    System.out.println("vb.getOid().size() < targetOID.size()");
    finished = true;
    }
    else if (targetOID.leftMostCompare(targetOID.size(),
    vb.getOid()) != 0)
    {
    //System.out.println("targetOID.leftMostCompare() != 0)");
    finished = true;
    }
    else if (Null.isExceptionSyntax(vb.getVariable().getSyntax()))
    {
    System.out.println(
    "Null.isExceptionSyntax(vb.getVariable().getSyntax())");
    finished = true;
    }
    else if (vb.getOid().compareTo(targetOID) <= 0)
    {
    System.out.println("Variable received is not "+
    "lexicographic successor of requested "+
    "one:");
    System.out.println(vb.toString() + " <= "+targetOID);
    finished = true;

    }
    else
    {
    // Dump response.
    System.out.println(vb.toString());

    // Set up the variable binding for the next entry.
    requestPDU.setRequestID(new Integer32(0));
    requestPDU.set(0, vb);
    }
    }

    snmp.close();

    }
    catch (IOException e)
    {
    System.out.println("IOException: "+e);
    }

    }

    }
    #

  5. #5
    syj
    syj est déconnecté
    Membre confirmé

    Profil pro
    DEV
    Inscrit en
    Septembre 2002
    Messages
    38
    Détails du profil
    Informations personnelles :
    Localisation : France, Seine Maritime (Haute Normandie)

    Informations professionnelles :
    Activité : DEV

    Informations forums :
    Inscription : Septembre 2002
    Messages : 38
    Par défaut
    Le code ci-dessus ne marchait pas pour moi, voici le mien si çà peut en aider d'autre.

    Il est inspiré du code:
    - org.snmp4j.tools.console.SnmpRequest
    - d'une autre discussion sur le forum : http://www.developpez.net/forums/d36...b/#post2747122

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
     
    /**
     * 
     */
    package eyes.snmp;
     
    import java.io.IOException;
    import java.util.List;
     
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.snmp4j.CommunityTarget;
    import org.snmp4j.PDU;
    import org.snmp4j.Snmp;
    import org.snmp4j.Target;
    import org.snmp4j.TransportMapping;
    import org.snmp4j.event.ResponseEvent;
    import org.snmp4j.event.ResponseListener;
    import org.snmp4j.mp.SnmpConstants;
    import org.snmp4j.smi.Address;
    import org.snmp4j.smi.GenericAddress;
    import org.snmp4j.smi.OID;
    import org.snmp4j.smi.OctetString;
    import org.snmp4j.smi.VariableBinding;
    import org.snmp4j.transport.DefaultUdpTransportMapping;
    import org.snmp4j.util.DefaultPDUFactory;
    import org.snmp4j.util.TreeEvent;
    import org.snmp4j.util.TreeListener;
    import org.snmp4j.util.TreeUtils;
     
     
     
    public class SnmpCommand implements ResponseListener {
        private static Log log = LogFactory.getLog(SnmpCommand.class);
     
        class WalkCounts {
            public int requests;
            public int objects;
        }
     
        String targetAddress;
        VariableBinding variableBinding;
     
        public SnmpCommand(String address) {
            this.targetAddress = address;
        }
     
        public void send(String oid, int ReqType) {
            Address targetAddress = GenericAddress.parse("udp:"
                    + this.targetAddress + "/161");
            TransportMapping transport = null;
            try {
                transport = new DefaultUdpTransportMapping();
            } catch (IOException e1) {
                log.error("Echec lors de l'initialisation du thread pour l'écoute des requetes UDP",e1);
            }
            Snmp snmp = new Snmp(transport);
     
            try {
                snmp.listen();
            } catch (IOException e) {
                e.printStackTrace();
            }
     
            // setting up target
            CommunityTarget target = new CommunityTarget();
            target.setCommunity(new OctetString("public"));
            target.setAddress(targetAddress);
            target.setRetries(2);
            target.setTimeout(1500);
            target.setVersion(SnmpConstants.version1);
            target.setTimeout(5000);
     
            // creating PDU
            PDU pdu = new PDU();
            pdu.add(new VariableBinding(new OID(oid)));
            pdu.setType(ReqType);
     
            // The Send Action
            try {
                snmp.send(pdu, target, null, this);
            } catch (IOException e) {
                log.error("Echec lors du lancement de la requete SNMP",e);
            }
     
            synchronized (this) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    log.warn("Tree retrieval interrupted: ",e);
                }
            }
     
        }
     
     
     
        public PDU createPDU(Target target) {
            PDU request;
     
                request = new PDU();
     
            request.setType(PDU.GETNEXT);
            return request;
        }
     
        public VariableBinding request(String oid) {
            send(oid, PDU.GET);
            return variableBinding;
        }
     
        public PDU walk(final List snapshot) throws IOException {
            // Adresse de la cible.
            Address targetAddress = GenericAddress.parse("udp:"
                    + this.targetAddress + "/161");
     
            // Type de transport.
            TransportMapping transport = null;
            try {
                transport = new DefaultUdpTransportMapping();
            } catch (IOException e1) {
                log.error("Echec lors de l'initialisation du thread pour l'écoute des requetes UDP",e1);
            }
     
            Snmp snmp = new Snmp(transport);
     
     
            // setting up target
            CommunityTarget target = new CommunityTarget();
            target.setCommunity(new OctetString("public"));
            target.setAddress(targetAddress);
            target.setRetries(2);
            target.setTimeout(1500);
            target.setVersion(SnmpConstants.version2c);
            target.setTimeout(5000);
     
            snmp.listen();
     
            PDU request =  createPDU(target);
            request.add(new VariableBinding(new OID("1.3.6")));
     
     
            request.setNonRepeaters(0);
     
            OID rootOID = request.get(0).getOid();
     
     
            PDU response = null;
            final WalkCounts counts = new WalkCounts();
            final long startTime = System.currentTimeMillis();
            TreeUtils treeUtils = new TreeUtils(snmp, new DefaultPDUFactory());
            TreeListener treeListener = new TreeListener() {
                public boolean next(TreeEvent e) {
                    counts.requests++;
                    if (e.getVariableBindings() != null) {
                        VariableBinding[] vbs = e.getVariableBindings();
                        counts.objects += vbs.length;
                        for (int i = 0; i < vbs.length; i++) {
                            if (snapshot != null) {
                                snapshot.add(vbs[i]);
                            }
                            System.out.println(vbs[i].toString());
                        }
                    }
                    return true;
                }
     
                public void finished(TreeEvent e) {
                    if ((e.getVariableBindings() != null)
                            && (e.getVariableBindings().length > 0)) {
                        next(e);
                    }
     
                    log.debug("Total requests sent:    "
                            + counts.requests);
                    log.debug("Total objects received: "
                            + counts.objects);
                    log.debug("Total walk time:        "
                            + (System.currentTimeMillis() - startTime)
                            + " milliseconds");
                    if (e.isError()) {
                        System.err
                                .println("The following error occurred during walk:");
                        System.err.println(e.getErrorMessage());
                    }
                    synchronized (this) {
                        this.notify();
                    }
                }
            };
            synchronized (treeListener) {
                treeUtils.getSubtree(target, rootOID, null, treeListener);
                try {
                    treeListener.wait();
                } catch (InterruptedException ex) {
                    log.warn("Tree retrieval interrupted: ",ex);
                    Thread.currentThread().interrupt();
                }
            }
            return response;
        }
     
        public void onResponse(ResponseEvent event) {
            synchronized (this) {
                ((Snmp) event.getSource()).cancel(event.getRequest(), this);
                this.variableBinding = event.getResponse().get(0);
     
                this.notify();    
            }        
        }
    }

  6. #6
    Membre averti
    Profil pro
    Inscrit en
    Août 2008
    Messages
    14
    Détails du profil
    Informations personnelles :
    Âge : 40
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations forums :
    Inscription : Août 2008
    Messages : 14
    Par défaut Amélioration ?
    Salut à tous,

    Je me suis permis d'apporter une petit modification à la fonction Walk (c'est elle qui m'intéressait). Elle ne retourne pas de PDU (car de toute façon, la PDU que tu retournais était Null, mais elle retourne une List des informations qui nous intéressent, à savoir : OID + valeur)

    Pour que tout ce petit monde fonctionne correctement, il faut spécifier au préalable (dans une autre fonction par exemple) les informations des variables :

    target

    Pour spécifier ces variables, reportez vous au code de syj

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
     
    public List<VariableBinding> walk( OID oid) throws IOException {
     
    		final List<VariableBinding> snapshot;
    		snapshot = new LinkedList<VariableBinding>();	
    		PDU request =  createPDU(target);
    		request.add(new VariableBinding(oid));
     
     
    		request.setNonRepeaters(0);
     
    		OID rootOID = request.get(0).getOid();
     
    		final WalkCounts counts = new WalkCounts();
    		final long startTime = System.currentTimeMillis();
    		TreeUtils treeUtils = new TreeUtils(snmp, new DefaultPDUFactory());
    		TreeListener treeListener = new TreeListener() {
    			public boolean next(TreeEvent e) {
    				counts.requests++;
    				if (e.getVariableBindings() != null) {
    					VariableBinding[] vbs = e.getVariableBindings();
    					counts.objects += vbs.length;
    					for (int i = 0; i < vbs.length; i++) {
    						if (snapshot != null) {
    							snapshot.add(vbs[i]);
    						}
    						System.out.println(vbs[i].toString());
    					}
    				}
    				return true;
    			}
     
    			public void finished(TreeEvent e) {
    				if ((e.getVariableBindings() != null)
    						&& (e.getVariableBindings().length > 0)) {
    					next(e);
    				}
     
    				log.debug("Total requests sent:    "
    						+ counts.requests);
    				log.debug("Total objects received: "
    						+ counts.objects);
    				log.debug("Total walk time:        "
    						+ (System.currentTimeMillis() - startTime)
    						+ " milliseconds");
    				if (e.isError()) {
    					System.err
    					.println("The following error occurred during walk:");
    					System.err.println(e.getErrorMessage());
    				}
    				synchronized (this) {
    					this.notify();
    				}
    			}
    		};
    		synchronized (treeListener) {
    			treeUtils.getSubtree(target, rootOID, null, treeListener);
    			try {
    				treeListener.wait();
    			} catch (InterruptedException ex) {
    				log.warn("Tree retrieval interrupted: ",ex);
    				Thread.currentThread().interrupt();
    			}
    		}
    		return snapshot;
    	}

    et pour appeler cette méthode, vous pouvez le faire de la manière suivante :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
    	List<VariableBinding> snapshot;
    	snapshot = null;
    	snapshot = mib.walk(new OID(".1.3.6.1.4.1.####.4.1.1.1"));
    Enfin, pour exploiter les résultat récupéré par mib.walk(...), dans la variable snapshot (j'ai pas pris la peine de changer les noms) :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    for (VariableBinding vb : snapshot){
    				System.out.println(vb.getOid());
    				System.out.println(vb.getSyntax());
    				System.out.println(vb.getVariable());
    			}
    En espérant que ça puisse vous aider à faire ce "snmpwalk" avec snmp4j.

    °°-

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Redémarer modem avec SNMP4J
    Par ilameq dans le forum API standards et tierces
    Réponses: 0
    Dernier message: 25/07/2012, 20h39
  2. comment je peut faire un snmpwalk avec snmp4j
    Par hamzawhy dans le forum Général Java
    Réponses: 0
    Dernier message: 02/05/2012, 01h39
  3. snmpwalk avec API windows?
    Par Persnip77 dans le forum C++
    Réponses: 1
    Dernier message: 18/07/2011, 14h46
  4. SNMP4j un problème avec les OIDs de la MIB2
    Par cassanova dans le forum API standards et tierces
    Réponses: 1
    Dernier message: 29/03/2010, 12h25
  5. agent snmp avec snmp4j
    Par ibyiby dans le forum Général Java
    Réponses: 0
    Dernier message: 23/09/2009, 21h31

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo