tutorial on managing UNIX-like systems using NET-SNMP under Ipython

Source: Internet
Author: User
Tags snmp snmp query snmpwalk version control system
Introduction

For Simple Network Management Protocol (SNMP), most system administrators have some experience of using it, or at least have heard of it. If you are working in a data center, you may be interacting with SNMP in some way every day. There are many impressive, same-sized network management systems (NMS) or network monitoring systems that use SNMP monitoring, but this article does not intend to introduce these systems. This article mainly deals with Python? Language to study SNMP and write related code in person.

A friend recently told me that sometimes it's like: just want to walk down the street to Grandma's house, without having to ride as fast as a Saturn V rocket. There are many tasks, if the use or configuration of large-scale NMS, it is like a Saturn V rocket, before filling the liquid oxygen tank, first try to use Python, then you will get better service. Learn how to write flexible Python code to interact with SNMP, which is probably one of the most interesting and efficient skills that a system administrator can get. Although SNMP is very complex to set up and use, the content discussed in this article will make it very interesting.
Installing and configuring NET-SNMP

To learn what's in this article, you'll need to install the latest Python (Python 2.3 or later) on your *nix computer. At the time of this writing, Python 2.5.1 is the latest version of Python. You also need to IPython to use the NET-SNMP library with Python bindings in an interactive manner. The NET-SNMP team tested the support in various operating systems in detail, including AIX, HP-UX, Gnu/linux? Distribution (such as Red Hat), Windows, or even OS X?.

Installing IPython is a very simple task. A good option is to use easy Install to manage Python packages. By running the ez_setup.py script, you can easily install any Python package. For example, you only need to type the following command:

Easy_install Ipython

Other optional installation options include using your favorite package management system, or simply download IPython and type the following command:

Python setup.py Install

Note that the trunk (trunk) refers to the root path in the version control system where the most recent copy of the code is saved. In addition, the trunk line also often represents a child version and version control system. For more details, see the sub-version links in the Resources section.

To learn the content in this article, you need to make sure that your client computer, or the computer running all the code, has NET-SNMP version 5.4.x or later, since this source code version includes a Python binding. In most cases, the installation of the bindings requires compiling the source files; However, you can also use Red Hat package Managers (RPM). If you are interested and have time, then you can view its latest version from the Net-snmp Web site.

There are many compile options to use, but the main task is to compile the net-snmp correctly, and then run the standalone Python installer in the Python directory. Another issue to note is that when you compile and run the./configure, it will run the configuration script of the local computer (the computer that is compiling the agent). You should not use this configuration script, for this article, you only need to create a simple configuration script.

Make a backup of the configuration files stored in/etc/snmp/snmpd.conf and build this very basic configuration:

Syslocation "My Local Machine" syscontact me@localhost.comrocommunity public

Save it and restart the snmpd daemon. In most *nix systems, you can use the/ETC/INIT.D/SNMPD restart to do the job.

Unless otherwise necessary, it is best not to compile the version that is in the active development phase, because doing so will require you to fix the problematic code yourself. In CentOS 5 or Red Hat Enterprise Linux 5 (RHEL 5), you can download the latest, stable source file RPM (5.4.1 version at the time of this writing). Note that you also need to use a Python source file to build the bindings. Therefore, if you are using a Red Hat-based computer, be sure to install Python-dev (or its equivalents) and Python Header files for a specific *nix operating system. If you need any help while building an RPM from a source file, please refer to the official Red Hat documentation. Building a package from a source file can be a very complex topic and is beyond the scope of this article. If you're having trouble using Python bindings, you should ask for help in the NET-SNMP mailing list.
To analyze the code

What are you waiting for? Suppose you already have Python bindings and IPython installed. Now you're ready to use IPython and start working on it. Although at some point, you may also want to browse the IPython documentation. Jeff Rush is the current Python advocacy Coordinator, and he provides some very good screen recordings for IPython. OK, let's start coding.

Let's make a simple query to identify a computer by using the computer's object identifier (OID) value, SYSDESCR. Start Ipython by typing Ipython, and then perform this interactive session:
Listing 1. IPython Example

In [1]: Import netsnmp in    [2]: oid = netsnmp. Varbind (' Sysdescr ') in    [3]: result = Netsnmp.snmpwalk (OID,    ...:             Version = 2,    ...:             desthost= " LocalHost ",    ...:             community=" public ") in    [4]: result = Netsnmp.snmpwalk (oid,                Version = 2,                desthost= "localhost",                community= "public") in    [+]: Result    out[16]: (' Linux localhost 2.6.18-8.1.14. El5 #1 SMP Thu Sep     18:58:54 EDT i686 ',)

Note that the result value you get is different from the result value shown here. If you have followed the configuration shown in Listing 1 above, then all other content should be available. If you are familiar with SNMP, you may soon be able to understand the actual effect of the content.

One of the benefits of using IPython to test an SNMP snippet is that it is like a normal shell, and that many basic, interactive shell concepts "can work", but it is necessary to note that they work in Python mode. Writing an SNMP code can be a very tedious activity, but using the NET-SNMP library with IPython makes it very interesting.

As you can see, the task is very simple to convert the result to a Python data type. That's why IPython and NET-SNMP can work together well. Now, for writing custom scripts, you only need to interactively parse the combinations of OIDs to query. Ideally, you need to run a large, easy-to-configure NMS provisioning script that automatically integrates the new computer into the network.

Of course, this is not the ideal situation, you need to know how to combine some good SNMP code together, for a system administrator, this is very useful. Here's an example scenario, assuming you've just converted a high-speed DDR to a 2-TB RAID 0 server running Ubuntu Linux, because you have to fix the problem in one hours, so you have to.

Now you're in a lot of trouble, and you only have a few minutes to monitor specific questions to see if you need to start sending resumes, or if you should start talking and ask for a promotion. Let's use the editing feature in IPython to write a script, save it to a file, and then run it in a session without leaving IPython: Ed snmpinput.py
Listing 2. Creation of the IPython module

Import Netsnmpclass Snmpsessionbaseclass (object): "" "  a Base Class for A SNMP Session" "  def __init__ (self,        Oid= "Sysdescr",        version=2,        desthost= "localhost",        community= "public"):    self.oid = oid self    . Version = Version Self    . Desthost = Desthost self    . Community = Community  def query (self): "" "    creates SNMP query session" ""    try:      result = Netsnmp.snmpwalk (self.oid,                  Version = self.) Version,                  desthost = self. Desthost,                  Community = self. Community)    except:      import sys      print sys.exc_info ()      result = None    return result

Customizing the IPython to use the correct editor

You can customize the Ipython by editing the $HOME/.IPYTHON/IPYTHONRC. One of the first things you need to customize is the%edit command, which you can invoke by typing ed. By default, it is set to use VI, but you can change it to use other editors, including Emacs. This article provides guidance on how to change your environment. You can also use the following command to start Ipython so that a specific editor is specified in hard-coded form: Ipython-editor=vim.

To continue, cut and paste the following code into the file you just created. When you save this file, IPython will run it automatically and place the class in the appropriate module in your environment. If you type who, you will see something similar to the following:

In [2]: Whonetsnmp snmpsessionbaseclass

This is a powerful feature because you can get all the benefits of using your favorite text editor (perhaps Vim or Emacs) and then use the code immediately in an interactive IPython Shell session. Note that if you have already written a module, you can also simply type and run it to get the same results. Execute and run the module in IPython, which is equivalent to running the code in it and putting it into the IPython environment.
Encode in an iterative way

Now by using IPython, you can combine the best features of the Python shell, the UNIX shell, and your favorite text editors. When interacting with very complex objects such as SNMP libraries, you need to use all the help you can get, and in this example, it really shows the power of IPython.

You can write some modules dynamically, and you can test and use them later. IPython can be well integrated with any programming style, including test-driven development (TDD) or test-enhanced development (TED). To prove this convenience, let's go to the module you just wrote.

Now that you have an object-oriented SNMP interface, you can start asking the local computer:
Listing 3. IPython Iterative Coding

In [1]: Run Snmpinputin [2]: WHONETSNMP snmpsessionbaseclass  inch [3]: s = snmpsessionbaseclass () in [4]: S.query () out[4] : (' Linux localhost 2.6.18-8.1.14.el5 #1 SMP Thu Sep 18:58:54 EDT i686 ',) in [5]: result = S.query () in [6]: Len (res ult) Out[6]: 1

It is very easy to get related results by using this module, but you are basically just running a hard-coded script, so you need to change the value of the OID object to traverse the system subtree:
Listing 4. Changing the value of an OID object

In [7]: s.oidout[7]: ' SYSDESCR ' in [8]: S.oid = ". 1.3.6.1.2.1.1" in [9]: result = S.query () in [ten]: Print result (' Linux loca Lhost 2.6.18-8.1.14.el5 #1 SMP Thu Sep 18:58:54 EDT i686 ',       '. 1.3.6.1.4.1.8072.3.2.10 ', ' 121219 ', ' me@localhost . com ',       ' localhost ', ' "My Local Machine" ', ' 0 ', '. 1.3.6.1.6.3.10.3.1.1 ', '. 1.3.6.1.6.3.11.3.1.1 ', '. 1.3.6.1.6.3.15.2.1.1 ', '. 1.3.6.1.6.3.1 ', '. 1.3.6.1.2.1.49 ', '. 1.3.6.1.2.1.4 ', '. 1.3.6.1.2.1.50 ', '. 1.3.6.1.6.3.16.2.2.1 ', ' The SNMP Management Architecture MiB. ', ' The MIB for Message processing and dispatching. ', ' the MA Nagement information definitions for the SNMP user-based Security Model. ', ' The MIB module for SNMPV2 entities ', ' the MIB Module for managing TCP implementations ', ' The MIB module formanaging IP and ICMP implementations ', ' The MIB module for MA Naging UDP implementations ', ' view-based Access Control Model for SNMP. ', ' 0 ', ' 0 ', ' 0 ', ' 0 ', ' 0 ', ' 0 ', ' 0 ', ' 0 ')

As you can see, it is very easy to use this module and start analyzing the entire network (one computer at a time). Carefully analyze and determine what needs to be queried on the network. This is another interesting feature of IPython and it is necessary to study it in depth. IPython has an incredible feature that allows you to run Python code snippets as a background process. Fortunately, this is a very simple operation. Let's run the same query again, but this time run it as a background process (see Listing 5).
Listing 5. IPython Iterative Coding example-background process

In [all]: BG S.query () starting job # 0 in a separate thread.  In [all]: jobs[0].statusout[12]: ' Completed ' in [+]: jobs[0].resultout[16]: (' Linux localhost 2.6.18-8.1.14.el5 #1 SMP Thu Sep 18:58:54 EDT i686 ', '. 1.3.6.1.4.1.8072.3.2.10 ', ' 121219 ', ' me@localhost.com ', ' localhost ', ' "My Local Machine "', ' 0 ', '. 1.3.6.1.6.3.10.3.1.1 ', '. 1.3.6.1.6.3.11.3.1.1 ', '. 1.3.6.1.6.3.15.2.1.1 ', '. 1.3.6.1.6.3.1 ', '. 1.3.6.1.2.1.49 ', '. 1.3.6.1.2.1.4 ', '. 1.3.6.1.2.1.50 ', '. 1.3.6.1.6.3.16.2.2.1 ', ' the SNMP Management Architecture MIB. ' , ' The MIB for Message processing and dispatching. ', ' The Management information definitions for the SNMP user-based secur ity Model. ', ' The MIB module for SNMPV2 entities ', ' the MIB module for managing TCP implementations ', ' the MIB module for  Managing IP and ICMP implementations ', ' the MIB module for managing UDP implementations ', ' view-based Access Control Model For SNMP. ', ' 0 ', ' 0 ', ' 0 ', ' 0 ', ' 0 ', ' 0 ', ' 0 ', ' 0 ')

It is exciting that the background thread in IPython is a valuable feature, but it can only work with libraries that support asynchronous threads. Unfortunately, the NET-SNMP is synchronous. If you are interested in this, you can test by changing the s.oid value to. iso. Before the query is complete, you should be aware that the IPython interpreter has "blocked" or "suspended". Although it is only a warning, the SNMP traversal of the entire. ISO tree may take a long time, so you might accept my point of view.

There is, of course, another solution. You can use one of the many processing libraries provided by Python to derive a new process for this blocked process. The Python Cheese Shop offers a number of third-party libraries. If you are using Easy_install, it will be fairly straightforward to install a package (such as Parallel Python) and test the library using NET-SNMP, so it will be up to you to decide.

Easy_install Http://www.parallelpython.com/downloads/pp/pp-1.5.zip

The last feature to show here is to run unit tests in the IPython Shell. When making changes to a module, it is very easy to run unit tests frequently. You need to add a tag to run RUN-E so that you can avoid backtracking to the unit test module in the IPython Shell. You can download this unit test in the source file that accompanies this article.

Note that IPython 0.8.2 also has a new document testing feature that allows you to generate document tests in IPython. Document testing is a good feature of Python because, along with other features, it provides a way to create testable documents for an API. Here is an example of how to run Doctest for our module in IPython:
Listing 6: Running IPython in doctest mode

In [5]:%doctest_mode*** Pasting of code with ">>>" or "..." has been enabled. Exception reporting Mode:plaindoctest mode is:on>>> from snmpinput import snmpsessionbaseclass>>> s = Snmpsessionbaseclass () >>> s.query (' Linux devmws2.racemi.com 2.6.9-55.0.2.el #1 Tue June-14:08:18 EDT I6 86 ',)

Because the doctest mode will execute the Python statement without parsing, you must be careful not to use the values that might change in doctest, just like the values given above. If you have pasted several lines of code in the docstring of the module, you can test your API documentation by using the following methods:

Def _test ():  import doctest  doctest.testmod () if __name__ = = "__main__":  _test ()

Summarize

In this article, you've learned that collaborative use of NET-SNMP and IPython will be a powerful combination. This article describes the following key concepts:

    • Python bindings: Net-snmp now provides Python bindings, which allows us to take full advantage of Python's capabilities to handle the SNMP protocol.
    • Processing libraries: Currently, Python bindings are synchronous, but using a processing library can derive a new process for each request to resolve the problem.
    • Flexible technology: IPython is a very mature and powerful tool for system administrators and software engineers. Although this article provides a brief introduction to several flexible technologies, such as document testing and unit testing, you can apply these techniques for any test-centric development, or to write and analyze code interactively.
    • SNMP and IPython: This article is just a brief introduction to the functionality that SNMP and IPython can achieve when used separately or together.

SNMP is so complex that it almost makes it unthinkable to write any meaningful code, but we hope that the techniques described in this article will inspire some new ideas. If you're curious to know exactly how far the SNMP Python implementation is, then you can study Zenoss, download a virtual machine, and test it. There is also an API that you can use to write scripts, so you can combine what you've learned here with a full Python NMS. Of course, it also applies to any other NMS.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.