Tutorial on using Net-SNMP in IPython to Manage UNIX systems

Source: Internet
Author: User
This article mainly introduces how to use Net-SNMP under IPython to Manage UNIX systems. This article is from the IBM official website technical documentation. For more information, see Introduction

Most system administrators have some experience in using the Simple Network Management Protocol (SNMP), or have heard of it at least. If you are working in a data center, you may interact with SNMP in some way every day. Many impressive network management systems (NMS) or network monitoring systems of the same size use SNMP monitoring, but this article does not intend to introduce these systems. This article mainly involves using Python? Language to study SNMP and write relevant code in person.

A friend recently told me that sometimes I encounter a situation like: I just want to walk along the street all the way to my grandmother's house without having to ride as fast as the Saturn V rocket. There are many tasks. if you use or configure large-scale NMS, it is like a Saturn V rocket. before filling up the liquid oxygen tank, try using Python first, then you will get better services. Learn how to write flexible Python code and interact with SNMP, which may be one of the most interesting and efficient skills that system administrators can obtain. Although the configuration and use of SNMP are complex, the content discussed in this article will make it very interesting.
Install and configure Net-SNMP

To learn more, install the latest Python (Python 2.3 or later) on your * nix computer ). At the time of writing this article, Python 2.5.1 is the latest version of Python. You also need IPython to use the Net-SNMP library bound with Python in interactive mode. The Net-SNMP team tested the support in various operating systems in detail, including AIX? , HP-UX? , GNU/Linux? Distribution version (such as Red Hat), Windows ?, Or even OS X ?.

Installing IPython is a simple task. A good choice 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 enter the following command:

easy_install ipython

Other optional installation methods include using your favorite package management system, or simply downloading IPython and typing the following command:

python setup.py install

Note that the trunk line (trunk) refers to the root path in the version control system, where the latest code copy is saved. In addition, trunk lines often represent a sub-version and version control system. For more details, see The Subversion link in the references section.

To learn about the content in this article, make sure that your client computer, or the computer that runs all the code has NET-SNMP Version 5.4.x or later installed, because starting with this source code Version, including Python binding. In most cases, the bound installation requires compiling the source file; however, you can also use Red Hat Package Manager (RPM ). If you are interested and have time, you can check the latest version of the Net-SNMP Web site.

There are a lot of compilation options to use, but the main task is to compile the NET-SNMP correctly and then run a standalone Python installer in the Python directory. Another issue that needs to be noted is that when you compile and run./configure, it will run the configuration script of the local computer (the computer that is compiling the proxy. You should not use this configuration script. for this article, you only need to create a simple configuration script.

Back up the configuration files stored in/etc/snmp/snmpd. conf and build the following 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/etc/init. d/snmpd restart to do this.

Unless you have to, it is best not to compile the version in the active development phase, because in this case, you will need to fix the problematic code by yourself. In CentOS 5 or Red Hat Enterprise Linux 5 (RHEL 5), you can download the latest and stable source file RPM (5.4.1 at the time of writing this article ). Note that you also need to use Python source files to build bindings. Therefore, if you are using a Red Hat-based computer, make sure that python-dev (or its equivalents) and Python Header files are installed for a specific * nix operating system. If you need any help when building an RPM from a source file, refer to the official Red Hat documentation. Building a package from a source file may be a very complex topic and beyond the scope of this article. If you have trouble binding Python, you should request help in the Net-SNMP email list.
Analyze code

What are you waiting? Assume that you have installed Python binding and IPython. Now you are ready to use IPython and start related work. Although in some cases, you may need to browse the IPython Documentation. Jeff Rush is the current Python Advocacy Coordinator. he provides IPython with some excellent screen recordings. Okay. let's start coding.

Let's perform a simple query to identify a computer by using the computer's object identifier (OID) value sysDescr. Start ipython by typing IPython, and then execute 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 [16]: result    Out[16]: ('Linux localhost 2.6.18-8.1.14.el5 #1 SMP Thu Sep 27     18:58:54 EDT 2007 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, all other content should be available. If you are familiar with SNMP, you may be able to understand the actual functions of the content immediately.

One of the advantages of using IPython to test SNMP code snippets is that it is like a common Shell, and many basic and interactive Shell concepts "can work ", however, it should be noted that they work in python mode. Writing SNMP code may be a very tedious activity, but using the Net-SNMP Library through IPython makes it very interesting.

As you can see, to convert the result to a Python data type, this task is very simple. This is why IPython and Net-SNMP can work together well. Now, for writing a custom script, you only need to analyze the combination of OID in interactive mode for query. Ideally, you need to run a large-scale, easy-to-configure NMS setup script to automatically integrate new computers into the network.

Of course, there is no such ideal situation. you need to know how to combine some good SNMP code. this is very useful for a system administrator. The following is an example. assume that you have just converted a high-speed DDR to a 2 tb raid 0 server running Ubuntu Linux, because you must solve the problem within one hour, so you have to do this.

Now you have a lot of trouble, and you only have a few minutes to monitor specific problems to see if you need to start sending your resume, or whether you should start preparing your speech and request a promotion. Let's use the editing function in IPython to compile the script, save it to the file, and then run it in a session without leaving IPython: ed snmpinput. py
Listing 2. Creating an 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

Customize IPython to use the correct editor

You can customize ipython by editing $ HOME/. Ipython/ipythonrc. First, you must run the % edit command. you can type ed to call this command. 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 to specify a specific editor: ipython-editor = vim in the form of hard encoding.

Run the following code and paste it into the file you just created. When you save this file, IPython runs it automatically and places it in the corresponding modules in your environment. If you type who, you will see something similar to the following:

In [2]: whonetsnmp snmpSessionBaseClass

This operation is very powerful, because you can get all the advantages of using your favorite text editor (maybe Vim or Emacs, then use the code immediately in the interactive IPython Shell session. Note that if you have compiled a module, you can simply type and run it to get the same result. Execute and run the module in IPython, which is equivalent to running the code and putting it into the IPython environment.
Code in iterative mode

By using IPython, you can combine Python Shell, UNIX Shell, and the best features of your favorite text editor. When interacting with very complex objects such as the SNMP library, you need to use all the help you can get. In this example, the powerful functions of IPython are truly displayed.

You can write some modules dynamically and 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 to ask the local computer:
Listing 3. IPython iterative encoding

In [1]: run snmpinputIn [2]: whonetsnmp snmpSessionBaseClass  In [3]: s = snmpSessionBaseClass()In [4]: s.query()Out[4]: ('Linux localhost 2.6.18-8.1.14.el5 #1 SMP Thu Sep 27 18:58:54 EDT 2007 i686',)In [5]: result = s.query()In [6]: len(result)Out[6]: 1

It is very easy to obtain relevant results by using this module, but you are basically only running a hardcoded script. Therefore, you need to change the value of the OID object to traverse the system subtree:
Listing 4. Changing the OID object value

In [7]: s.oidOut[7]: 'sysDescr'In [8]: s.oid = ".1.3.6.1.2.1.1"In [9]: result = s.query()In [10]: print result('Linux localhost 2.6.18-8.1.14.el5 #1 SMP Thu Sep 27 18:58:54 EDT 2007 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 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 managing 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 to analyze the entire network (one computer at a time. Perform a careful analysis and determine the content 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 background processes. Fortunately, this operation is very simple. Let's run the same query again, but this time we run it as a background process (see listing 5 ).
Listing 5. IPython iterative encoding example-background process

In [11]: bg s.query()Starting job # 0 in a separate thread.In [12]: jobs[0].statusOut[12]: 'Completed'In [16]: jobs[0].resultOut[16]: ('Linux localhost 2.6.18-8.1.14.el5 #1 SMP Thu Sep 27 18:58:54 EDT 2007 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 Security 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 very valuable function, but it can only work with libraries that support asynchronous threads. Unfortunately, Net-SNMP is synchronized. If you are interested in this, you can change the s. oid value to. iso for testing. Before the query is complete, you should note that the IPython interpreter is blocked or suspended ". Although it is only a warning, SNMP traversal of the entire. iso tree may take a long time, so you may accept my opinion.

Of course, there is another solution. You can use one of the many processing libraries provided by Python to derive new processes from this BLOCKED process. Python Cheese Shop provides some third-party libraries. If you are using easy_install, it is quite easy to install a package (such as Parallel Python) and use Net-SNMP to test the library, so it is up to you to decide.

easy_install http://www.parallelpython.com/downloads/pp/pp-1.5.zip

The last feature to be presented here is to run the unit test in IPython Shell. When changing a module, you need to run the unit test frequently, which is also very easy. You need to add a flag to run-e, so that you can avoid backtracing to the unit test module in IPython Shell. You can download this unit test from the source file attached to this document.

Note that IPython 0.8.2 also has a new document test feature that allows you to generate document tests in IPython. Document testing is a good feature of Python, because, together with other features, it provides a way to create testable documents for APIs. The following example shows how to run doctest for our module in IPython:
Listing 6. run 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 Jun 26 14:08:18 EDT 2007 i686',)

Because the doctest mode executes Python statements without analysis, you must be careful not to use the value that may be changed in doctest, just like the value given above. If you have pasted several lines of code in the docstring of the module, you can use the following method to test your API documentation:

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

Summary

In this article, you have learned that collaborative use of Net-SNMP and IPython will become a powerful combination of functions. This article introduces the following concepts:

  • Python binding: Net-SNMP now provides Python binding, which allows us to take full advantage of the Python function to process the SNMP protocol.
  • Processing database: currently, Python binding is synchronous, but you can use the processing database to derive a new process for each request to solve this problem.
  • Flexible Technology: for system administrators and software engineers, IPython is a very mature and powerful tool. Although this article only briefly introduces several flexible technologies, such as document testing and unit testing, you can apply these technologies, perform any test-centered development or write and analyze code in an interactive manner.
  • SNMP and IPython: This article briefly introduces the functions that SNMP and IPython can implement when they are used independently or jointly.

SNMP is very complex, and it almost makes people afraid to write any meaningful code. However, we hope the technology introduced in this article can inspire some new ideas. If you are curious about how much Python implements SNMP, 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 the content learned here with the full Python NMS. Of course, it also applies to any other NMS.

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.