A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service
For Simple Network Management Protocol (SNMP), most system administrators have some experience with it, or at least they have heard of it. If you are working in a data center, you may interact with SNMP in some way every day. There are many impressive, equally 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 is mainly concerned with the use of Python? Language to study SNMP and write related code for yourself.
A friend recently told me that sometimes it was like this: I just wanted to walk down the street to Granny's house without having to ride as fast as the Saturn V rocket. There are many tasks, if you use or configure a large-scale NMS, it is like a Saturn V rocket, before filling the tank, try to use Python, then you will get better service. Learn how to write flexible Python code to interact with SNMP, which may be one of the most interesting and efficient skills that a system administrator can get. Although the setup and use of SNMP is very complex, the content discussed in this article will make it very interesting.
Installing and configuring NET-SNMP
To learn the content of this article, you need to install the latest Python (that is, Python 2.3 or later) on your *nix computer. At the time of this writing, Python 2.5.1 was the latest version of Python. You also need to IPython to use a NET-SNMP library that is bound with Python in an interactive way. 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?, and even OS X?.
Installing IPython is a very 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 type the following command:
Other optional installation options include using your favorite package management system, or simply downloading IPython and typing 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 often represents a version and versioning system. For more detailed information, see the sub-version link in the Resources section.
To learn the content of this article, you need to make sure that your client computer, or the computer that is running all the code, has NET-SNMP version 5.4.x or later, because it starts with the source code version, including the Python bindings. In most cases, the installation of a binding requires that the source file be compiled, but Red Hat Package managers (RPM) can also be used. If you have interest and time, you can view the latest version of it from the Net-snmp Web site.
There are many compilation options available, 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./configure, it will run the configuration script for the local computer (the computer that is compiling the agent). You should not use this configuration script, for the purposes of this article, you only need to create a simple configuration script.
Back up the configuration files stored in the/etc/snmp/snmpd.conf and build the following very basic configuration:
Syslocation ' My local Machine ' syscontact email@example.com rocommunity Public
Save it and restart the snmpd daemon. In most *nix systems,/ETC/INIT.D/SNMPD Restart can be used to do this work.
Unless, in the last resort, it is best not to compile the version that is in the active development phase, because you will need to fix the problematic code yourself. In CentOS 5 or Red Hat Enterprise Linux 5 (RHEL 5), you can download the latest, stable source RPM (5.4.1 version at the time of this writing). Note that you also need to use the Python source file to build the bindings. Therefore, if you are using a Red Hat based computer, be sure to install the Python-dev (or its equivalent) and the Python Header file for a specific *nix operating system. If you need any help in building RPM from a source file, refer to the official Red Hat document. 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.
What are you waiting for? Let's say you have the Python bindings and IPython installed. Now you're ready to use IPython and start working on it. Although at some point you may also need to browse the IPython document. Jeff Rush is the current Python advocacy Coordinator, and he provides IPython with some very good screen video content. 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 sample
In : Import netsnmp in : oid = netsnmp. Varbind (' SYSDESCR ') in : result = Netsnmp.snmpwalk (OID, ...: Version = 2, ...: desthost= " LocalHost ", ...: community=" public ") in : result = Netsnmp.snmpwalk (oid, Version = 2, desthost= "localhost", community= "public") in [-]: Result out: (' Linux localhost 2.6.18-8.1.14. El5 #1 SMP Thu Sep 18:58:54 EDT 2007 i686 ',)
Note that the result you obtained is different from the resulting 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 soon be able to understand the actual role of these elements.
One of the benefits of using IPython to test an SNMP snippet is that it's like an ordinary shell, and many basic, interactive shell concepts "can work", but it should be explained that they work in a python way. Writing SNMP code can be a very tedious activity, but using the NET-SNMP library through IPython makes it very interesting.
As you can see, the task is very simple to convert the results to Python data types. That's why IPython and NET-SNMP can work together well. Now, for writing a custom script, you just need to interactively parse the combination of OIDs for querying. Ideally, a large, easily configurable NMS setup script needs to be run to automate the integration of new computers into the network.
Of course, this is not the ideal situation, you need to know how to combine some good SNMP code together, this is very useful for a system administrator. 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 within one hours, so you have to.
Now you're in a lot of trouble and you only have a few minutes to monitor specific issues to see if you need to start sending resumes, or if you should start preparing a speech and asking for a promotion. Let's use the editing feature in IPython to write the script, save it to a file, and then run it in a session without leaving IPython: Ed snmpinput.py
Listing 2. Creation of IPython Modules
Import NETSNMP class Snmpsessionbaseclass (object): "" " a Base class for an 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 Ipython by editing the $HOME/.IPYTHON/IPYTHONRC. One of the first things you need to customize is the%edit command, which you can call by typing ed. By default, it is set to use VI, but you can change it to use other editors, including Emacs. This article gives guidance on how to change your environment. You can also use the following command to start Ipython to specify the use of a specific editor in hard-coded form: Ipython-editor=vim.
Continue, cut and paste the following code into the file you just created. When you save the file, IPython runs it automatically and places the class in the appropriate module in your environment. If you type who, you will see something similar to the following:
In : Who netsnmp 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 that code immediately in an interactive IPython Shell session. Note that if you have 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 and putting it into the IPython environment.
coding in an iterative fashion
Now by using IPython, you can combine the best features of the Python shell, the UNIX shell, and 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, and in this example, you really show 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 your local computer:
Listing 3. IPython-Iterative coding
In : Run Snmpinput in : Who netsnmp snmpsessionbaseclass in : s = Snmpsessionbaseclass () in : S.query () out: (' Linux localhost 2.6.18-8.1.14.el5 #1 SMP Thu Sep 18:58:54 EDT 2007 i686 ',) in : Result = S.query () in : Len (Result) Out: 1
It's easy to get related results by using this module, but you're 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. Change the value of an OID object
: s.oid out: ' SYSDESCR ' in : S.oid =". 188.8.131.52.2.1.1 "in : result = S.que Ry () in [ten]: Print result (' Linux localhost 2.6.18-8.1.14.el5 #1 SMP Thu Sep 18:58:54 EDT 2007 ', '. i686. 184.108.40.206220.127.116.11 ', ' 121219 ', ' firstname.lastname@example.org ', ' localhost ', ' my local Machine ', ' 0 ', '. 18.104.22.168.22.214.171.124.1.1 ', '. 126.96.36.199.188.8.131.52.1.1 ', '. 184.108.40.206.220.127.116.11.1.1 ', '. 18.104.22.168.6.3.1 ', '. 22.214.171.124.2.1.49 ', '. 126.96.36.199.2.1.4 ', '. 188.8.131.52.2.1.50 ', '. 184.108.40.206.220.127.116.11.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 SNMP V2 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 ')
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 a Python snippet as a background process. Fortunately, this is a very simple operation. Let's run the same query again, but this time it runs as a background process (see Listing 5).
Listing 5. IPython Iterative Encoding Example--background process
in [one]: BG s.query () starting job # 0 in a separate thread. in [[): Jobs.status out: ' Completed ' in : Jobs.result out: (' Linux localhost 2.6.18-8.1.14.el5 #1 SMP Thu Sep 18:58:54 EDT 2007 i686 ', '. 18.104.22.168.4.1.8072.3.2.10 ', ' 121219 ', ' email@example.com ', ' localhost ', ' "my local M Achine "', ' 0 ', '. 22.214.171.124.126.96.36.199.1.1 ', '. 188.8.131.52.184.108.40.206.1.1 ', '. 220.127.116.11.18.104.22.168.1.1 ', '. 22.214.171.124.6.3.1 ', '. 126.96.36.199.2.1.49 ', '. 188.8.131.52.2.1.4 ', '. 184.108.40.206.2.1.50 ', '. 220.127.116.11.18.104.22.168.2.1 ', ' The SNMP Management architecture MIB. ' , ' The MIB for message processing and dispatching ', ' The Management information definitions for the SNMP user-based Sec Urity Model. ', ' The MIB module for SNMPV2 entities ', ' the MIB module for managing TCP implementations ', ' the MIB module F or 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 are synchronized. 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 "hangs". Although it is only a warning, SNMP traversal of the entire. ISO tree can take a long time, so you may accept my point of view.
There is, of course, another solution. You can derive a new process for this blocked process by using one of the many processing libraries provided by Python. The Python Cheese Shop offers some third-party libraries. If you are using Easy_install, it will be quite straightforward to install a package (such as Parallel Python) and test the library with NET-SNMP, so it is up to you to decide.
The last feature to show here is to run unit tests in the IPython Shell. When you make changes to a module, you need to run unit tests frequently, which is also very easy. 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 files that are included with this article.
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, along with other features, it provides a way to create testable documents for an API. Here's an example to show how to run Doctest for our module in IPython:
Listing 6. Running in doctest mode IPython
In :%doctest_mode * * Pasting of code with ">>>" or "..." has been enabled. Exception reporting Mode:plain doctest 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 2007 i686 ',)
Because the doctest mode will execute the Python statement without parsing, you must be careful not to use a value that might be changed in the doctest, like the value given above. If you paste several lines of code into the docstring of a module, you can test your API documentation by using the following methods:
Def _test (): import doctest doctest.testmod () if __name__ = = "__main__": _test ()
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:
SNMP is so complex that it makes it almost impossible to imagine writing 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 SNMP's Python implementations are, you can study Zenoss, download a virtual machine, and test it. There's also an API that you can use to write scripts, so you can combine what you've learned here with a comprehensive Python NMS. Of course, it also applies to any other NMS.
Start building with 50+ products and up to 12 months usage for Elastic Compute Service