pynetsnmp-0.28.14/000755 000765 000765 00000000000 11330646327 013652 5ustar00chetchet000000 000000 pynetsnmp-0.28.14/CONSTANTS.py000644 000765 000765 00000026557 11330646327 015617 0ustar00chetchet000000 000000 USM_LENGTH_OID_TRANSFORM = 10 NULL = None MAX_CALLBACK_IDS = 2 MAX_CALLBACK_SUBIDS = 16 SNMP_CALLBACK_LIBRARY = 0 SNMP_CALLBACK_APPLICATION = 1 SNMP_CALLBACK_POST_READ_CONFIG = 0 SNMP_CALLBACK_STORE_DATA = 1 SNMP_CALLBACK_SHUTDOWN = 2 SNMP_CALLBACK_POST_PREMIB_READ_CONFIG = 3 SNMP_CALLBACK_LOGGING = 4 SNMP_CALLBACK_SESSION_INIT = 5 PARSE_PACKET = 0 DUMP_PACKET = 1 MAX_SUBID = 0xFFFFFFFF MAX_SUBID = 0xFF MIN_OID_LEN = 2 MAX_OID_LEN = 128 MAX_NAME_LEN = MAX_OID_LEN ASN_BOOLEAN = (0x01) ASN_INTEGER = (0x02) ASN_BIT_STR = (0x03) ASN_OCTET_STR = (0x04) ASN_NULL = (0x05) ASN_OBJECT_ID = (0x06) ASN_SEQUENCE = (0x10) ASN_SET = (0x11) ASN_UNIVERSAL = (0x00) ASN_APPLICATION = (0x40) ASN_CONTEXT = (0x80) ASN_PRIVATE = (0xC0) ASN_PRIMITIVE = (0x00) ASN_CONSTRUCTOR = (0x20) ASN_LONG_LEN = (0x80) ASN_EXTENSION_ID = (0x1F) ASN_BIT8 = (0x80) ASN_OPAQUE_TAG1 = (ASN_CONTEXT | ASN_EXTENSION_ID) ASN_OPAQUE_TAG2 = (0x30) ASN_OPAQUE_TAG2U = (0x2f) ASN_APP_OPAQUE = (ASN_APPLICATION | 4) ASN_APP_COUNTER64 = (ASN_APPLICATION | 6) ASN_APP_FLOAT = (ASN_APPLICATION | 8) ASN_APP_DOUBLE = (ASN_APPLICATION | 9) ASN_APP_I64 = (ASN_APPLICATION | 10) ASN_APP_U64 = (ASN_APPLICATION | 11) ASN_APP_UNION = (ASN_PRIVATE | 1) ASN_OPAQUE_COUNTER64 = (ASN_OPAQUE_TAG2 + ASN_APP_COUNTER64) ASN_OPAQUE_COUNTER64_MX_BER_LEN = 12 ASN_OPAQUE_FLOAT = (ASN_OPAQUE_TAG2 + ASN_APP_FLOAT) ASN_OPAQUE_FLOAT_BER_LEN = 7 ASN_OPAQUE_DOUBLE = (ASN_OPAQUE_TAG2 + ASN_APP_DOUBLE) ASN_OPAQUE_DOUBLE_BER_LEN = 11 ASN_OPAQUE_I64 = (ASN_OPAQUE_TAG2 + ASN_APP_I64) ASN_OPAQUE_I64_MX_BER_LEN = 11 ASN_OPAQUE_U64 = (ASN_OPAQUE_TAG2 + ASN_APP_U64) ASN_OPAQUE_U64_MX_BER_LEN = 12 ASN_PRIV_INCL_RANGE = (ASN_PRIVATE | 2) ASN_PRIV_EXCL_RANGE = (ASN_PRIVATE | 3) ASN_PRIV_DELEGATED = (ASN_PRIVATE | 5) ASN_PRIV_IMPLIED_OCTET_STR = (ASN_PRIVATE | ASN_OCTET_STR) ASN_PRIV_IMPLIED_OBJECT_ID = (ASN_PRIVATE | ASN_OBJECT_ID) ASN_PRIV_RETRY = (ASN_PRIVATE | 7) SNMP_PORT = 161 SNMP_TRAP_PORT = 162 SNMP_MAX_LEN = 1500 SNMP_MIN_MAX_LEN = 484 SNMP_VERSION_1 = 0 SNMP_VERSION_2c = 1 SNMP_VERSION_2u = 2 SNMP_VERSION_3 = 3 SNMP_VERSION_sec = 128 SNMP_VERSION_2p = 129 SNMP_VERSION_2star = 130 SNMP_MSG_GET = (ASN_CONTEXT | ASN_CONSTRUCTOR | 0x0) SNMP_MSG_GETNEXT = (ASN_CONTEXT | ASN_CONSTRUCTOR | 0x1) SNMP_MSG_RESPONSE = (ASN_CONTEXT | ASN_CONSTRUCTOR | 0x2) SNMP_MSG_SET = (ASN_CONTEXT | ASN_CONSTRUCTOR | 0x3) SNMP_MSG_TRAP = (ASN_CONTEXT | ASN_CONSTRUCTOR | 0x4) SNMP_MSG_GETBULK = (ASN_CONTEXT | ASN_CONSTRUCTOR | 0x5) SNMP_MSG_INFORM = (ASN_CONTEXT | ASN_CONSTRUCTOR | 0x6) SNMP_MSG_TRAP2 = (ASN_CONTEXT | ASN_CONSTRUCTOR | 0x7) SNMP_MSG_REPORT = (ASN_CONTEXT | ASN_CONSTRUCTOR | 0x8) SNMP_MSG_INTERNAL_SET_BEGIN = -1 SNMP_MSG_INTERNAL_SET_RESERVE1 = 0 SNMP_MSG_INTERNAL_SET_RESERVE2 = 1 SNMP_MSG_INTERNAL_SET_ACTION = 2 SNMP_MSG_INTERNAL_SET_COMMIT = 3 SNMP_MSG_INTERNAL_SET_FREE = 4 SNMP_MSG_INTERNAL_SET_UNDO = 5 SNMP_MSG_INTERNAL_SET_MAX = 6 SNMP_MSG_INTERNAL_CHECK_VALUE = 17 SNMP_MSG_INTERNAL_ROW_CREATE = 18 SNMP_MSG_INTERNAL_UNDO_SETUP = 19 SNMP_MSG_INTERNAL_SET_VALUE = 20 SNMP_MSG_INTERNAL_CHECK_CONSISTENCY = 21 SNMP_MSG_INTERNAL_UNDO_SET = 22 SNMP_MSG_INTERNAL_COMMIT = 23 SNMP_MSG_INTERNAL_UNDO_COMMIT = 24 SNMP_MSG_INTERNAL_IRREVERSIBLE_COMMIT = 25 SNMP_MSG_INTERNAL_UNDO_CLEANUP = 26 SNMP_MSG_INTERNAL_PRE_REQUEST = 128 SNMP_MSG_INTERNAL_OBJECT_LOOKUP = 129 SNMP_MSG_INTERNAL_POST_REQUEST = 130 SNMP_MSG_INTERNAL_GET_STASH = 131 SNMP_NOSUCHOBJECT = (ASN_CONTEXT | ASN_PRIMITIVE | 0x0) SNMP_NOSUCHINSTANCE = (ASN_CONTEXT | ASN_PRIMITIVE | 0x1) SNMP_ENDOFMIBVIEW = (ASN_CONTEXT | ASN_PRIMITIVE | 0x2) SNMP_ERR_NOERROR = (0) SNMP_ERR_TOOBIG = (1) SNMP_ERR_NOSUCHNAME = (2) SNMP_ERR_BADVALUE = (3) SNMP_ERR_READONLY = (4) SNMP_ERR_GENERR = (5) SNMP_ERR_NOACCESS = (6) SNMP_ERR_WRONGTYPE = (7) SNMP_ERR_WRONGLENGTH = (8) SNMP_ERR_WRONGENCODING = (9) SNMP_ERR_WRONGVALUE = (10) SNMP_ERR_NOCREATION = (11) SNMP_ERR_INCONSISTENTVALUE = (12) SNMP_ERR_RESOURCEUNAVAILABLE = (13) SNMP_ERR_COMMITFAILED = (14) SNMP_ERR_UNDOFAILED = (15) SNMP_ERR_AUTHORIZATIONERROR = (16) SNMP_ERR_NOTWRITABLE = (17) SNMP_ERR_INCONSISTENTNAME = (18) MAX_SNMP_ERR = 18 SNMP_TRAP_COLDSTART = (0) SNMP_TRAP_WARMSTART = (1) SNMP_TRAP_LINKDOWN = (2) SNMP_TRAP_LINKUP = (3) SNMP_TRAP_AUTHFAIL = (4) SNMP_TRAP_EGPNEIGHBORLOSS = (5) SNMP_TRAP_ENTERPRISESPECIFIC = (6) SNMP_ROW_NONEXISTENT = 0 SNMP_ROW_ACTIVE = 1 SNMP_ROW_NOTINSERVICE = 2 SNMP_ROW_NOTREADY = 3 SNMP_ROW_CREATEANDGO = 4 SNMP_ROW_CREATEANDWAIT = 5 SNMP_ROW_DESTROY = 6 SNMP_STORAGE_NONE = 0 SNMP_STORAGE_OTHER = 1 SNMP_STORAGE_VOLATILE = 2 SNMP_STORAGE_NONVOLATILE = 3 SNMP_STORAGE_PERMANENT = 4 SNMP_STORAGE_READONLY = 5 SNMP_MP_MODEL_SNMPv1 = 0 SNMP_MP_MODEL_SNMPv2c = 1 SNMP_MP_MODEL_SNMPv2u = 2 SNMP_MP_MODEL_SNMPv3 = 3 SNMP_MP_MODEL_SNMPv2p = 256 SNMP_SEC_MODEL_ANY = 0 SNMP_SEC_MODEL_SNMPv1 = 1 SNMP_SEC_MODEL_SNMPv2c = 2 SNMP_SEC_MODEL_USM = 3 SNMP_SEC_MODEL_SNMPv2p = 256 SNMP_SEC_LEVEL_NOAUTH = 1 SNMP_SEC_LEVEL_AUTHNOPRIV = 2 SNMP_SEC_LEVEL_AUTHPRIV = 3 SNMP_MSG_FLAG_AUTH_BIT = 0x01 SNMP_MSG_FLAG_PRIV_BIT = 0x02 SNMP_MSG_FLAG_RPRT_BIT = 0x04 UCD_MSG_FLAG_RESPONSE_PDU = 0x100 UCD_MSG_FLAG_EXPECT_RESPONSE = 0x200 UCD_MSG_FLAG_FORCE_PDU_COPY = 0x400 UCD_MSG_FLAG_ALWAYS_IN_VIEW = 0x800 UCD_MSG_FLAG_PDU_TIMEOUT = 0x1000 UCD_MSG_FLAG_ONE_PASS_ONLY = 0x2000 SNMP_VIEW_INCLUDED = 1 SNMP_VIEW_EXCLUDED = 2 SNMP_OID_INTERNET = 1, 3, 6, 1 SNMP_OID_ENTERPRISES = SNMP_OID_INTERNET, 4, 1 SNMP_OID_MIB2 = SNMP_OID_INTERNET, 2, 1 SNMP_OID_SNMPV2 = SNMP_OID_INTERNET, 6 SNMP_OID_SNMPMODULES = SNMP_OID_SNMPV2, 3 SNMPADMINLENGTH = 255 USM_AUTH_KU_LEN = 32 USM_PRIV_KU_LEN = 32 SNMP_DEFAULT_COMMUNITY_LEN = 0 SNMP_DEFAULT_RETRIES = -1 SNMP_DEFAULT_TIMEOUT = -1 SNMP_DEFAULT_REMPORT = 0 SNMP_DEFAULT_REQID = -1 SNMP_DEFAULT_MSGID = -1 SNMP_DEFAULT_ERRSTAT = -1 SNMP_DEFAULT_ERRINDEX = -1 SNMP_DEFAULT_ADDRESS = 0 SNMP_DEFAULT_PEERNAME = NULL SNMP_DEFAULT_ENTERPRISE_LENGTH = 0 SNMP_DEFAULT_TIME = 0 SNMP_DEFAULT_VERSION = -1 SNMP_DEFAULT_SECMODEL = -1 SNMP_DEFAULT_CONTEXT = "" SNMP_DEFAULT_AUTH_PROTOLEN = USM_LENGTH_OID_TRANSFORM SNMP_DEFAULT_PRIV_PROTOLEN = USM_LENGTH_OID_TRANSFORM SNMP_MAX_MSG_SIZE = 1472 SNMP_MAX_MSG_V3_HDRS = (4+3+4+7+7+3+7+16) SNMP_MAX_ENG_SIZE = 32 SNMP_MAX_SEC_NAME_SIZE = 256 SNMP_MAX_CONTEXT_SIZE = 256 SNMP_SEC_PARAM_BUF_SIZE = 256 SNMPV3_IGNORE_UNAUTH_REPORTS = 0 SNMP_SESS_NONAUTHORITATIVE = 0 SNMP_SESS_AUTHORITATIVE = 1 SNMP_SESS_UNKNOWNAUTH = 2 REPORT_STATS_LEN = 9 REPORT_snmpUnknownSecurityModels_NUM = 1 REPORT_snmpInvalidMsgs_NUM = 2 REPORT_usmStatsUnsupportedSecLevels_NUM = 1 REPORT_usmStatsNotInTimeWindows_NUM = 2 REPORT_usmStatsUnknownUserNames_NUM = 3 REPORT_usmStatsUnknownEngineIDs_NUM = 4 REPORT_usmStatsWrongDigests_NUM = 5 REPORT_usmStatsDecryptionErrors_NUM = 6 SNMP_DETAIL_SIZE = 512 SNMP_FLAGS_USER_CREATED = 0x200 SNMP_FLAGS_DONT_PROBE = 0x100 SNMP_FLAGS_STREAM_SOCKET = 0x80 SNMP_FLAGS_LISTENING = 0x40 SNMP_FLAGS_SUBSESSION = 0x20 SNMP_FLAGS_STRIKE2 = 0x02 SNMP_FLAGS_STRIKE1 = 0x01 SNMPERR_SUCCESS = (0) SNMPERR_GENERR = (-1) SNMPERR_BAD_LOCPORT = (-2) SNMPERR_BAD_ADDRESS = (-3) SNMPERR_BAD_SESSION = (-4) SNMPERR_TOO_LONG = (-5) SNMPERR_NO_SOCKET = (-6) SNMPERR_V2_IN_V1 = (-7) SNMPERR_V1_IN_V2 = (-8) SNMPERR_BAD_REPEATERS = (-9) SNMPERR_BAD_REPETITIONS = (-10) SNMPERR_BAD_ASN1_BUILD = (-11) SNMPERR_BAD_SENDTO = (-12) SNMPERR_BAD_PARSE = (-13) SNMPERR_BAD_VERSION = (-14) SNMPERR_BAD_SRC_PARTY = (-15) SNMPERR_BAD_DST_PARTY = (-16) SNMPERR_BAD_CONTEXT = (-17) SNMPERR_BAD_COMMUNITY = (-18) SNMPERR_NOAUTH_DESPRIV = (-19) SNMPERR_BAD_ACL = (-20) SNMPERR_BAD_PARTY = (-21) SNMPERR_ABORT = (-22) SNMPERR_UNKNOWN_PDU = (-23) SNMPERR_TIMEOUT = (-24) SNMPERR_BAD_RECVFROM = (-25) SNMPERR_BAD_ENG_ID = (-26) SNMPERR_BAD_SEC_NAME = (-27) SNMPERR_BAD_SEC_LEVEL = (-28) SNMPERR_ASN_PARSE_ERR = (-29) SNMPERR_UNKNOWN_SEC_MODEL = (-30) SNMPERR_INVALID_MSG = (-31) SNMPERR_UNKNOWN_ENG_ID = (-32) SNMPERR_UNKNOWN_USER_NAME = (-33) SNMPERR_UNSUPPORTED_SEC_LEVEL = (-34) SNMPERR_AUTHENTICATION_FAILURE = (-35) SNMPERR_NOT_IN_TIME_WINDOW = (-36) SNMPERR_DECRYPTION_ERR = (-37) SNMPERR_SC_GENERAL_FAILURE = (-38) SNMPERR_SC_NOT_CONFIGURED = (-39) SNMPERR_KT_NOT_AVAILABLE = (-40) SNMPERR_UNKNOWN_REPORT = (-41) SNMPERR_USM_GENERICERROR = (-42) SNMPERR_USM_UNKNOWNSECURITYNAME = (-43) SNMPERR_USM_UNSUPPORTEDSECURITYLEVEL = (-44) SNMPERR_USM_ENCRYPTIONERROR = (-45) SNMPERR_USM_AUTHENTICATIONFAILURE = (-46) SNMPERR_USM_PARSEERROR = (-47) SNMPERR_USM_UNKNOWNENGINEID = (-48) SNMPERR_USM_NOTINTIMEWINDOW = (-49) SNMPERR_USM_DECRYPTIONERROR = (-50) SNMPERR_NOMIB = (-51) SNMPERR_RANGE = (-52) SNMPERR_MAX_SUBID = (-53) SNMPERR_BAD_SUBID = (-54) SNMPERR_LONG_OID = (-55) SNMPERR_BAD_NAME = (-56) SNMPERR_VALUE = (-57) SNMPERR_UNKNOWN_OBJID = (-58) SNMPERR_NULL_PDU = (-59) SNMPERR_NO_VARS = (-60) SNMPERR_VAR_TYPE = (-61) SNMPERR_MALLOC = (-62) SNMPERR_KRB5 = (-63) SNMPERR_PROTOCOL = (-64) SNMPERR_MAX = (-64) NETSNMP_CALLBACK_OP_RECEIVED_MESSAGE = 1 NETSNMP_CALLBACK_OP_TIMED_OUT = 2 NETSNMP_CALLBACK_OP_SEND_FAILED = 3 NETSNMP_CALLBACK_OP_CONNECT = 4 NETSNMP_CALLBACK_OP_DISCONNECT = 5 STAT_SNMPUNKNOWNSECURITYMODELS = 0 STAT_SNMPINVALIDMSGS = 1 STAT_SNMPUNKNOWNPDUHANDLERS = 2 STAT_MPD_STATS_START = STAT_SNMPUNKNOWNSECURITYMODELS STAT_MPD_STATS_END = STAT_SNMPUNKNOWNPDUHANDLERS STAT_USMSTATSUNSUPPORTEDSECLEVELS = 3 STAT_USMSTATSNOTINTIMEWINDOWS = 4 STAT_USMSTATSUNKNOWNUSERNAMES = 5 STAT_USMSTATSUNKNOWNENGINEIDS = 6 STAT_USMSTATSWRONGDIGESTS = 7 STAT_USMSTATSDECRYPTIONERRORS = 8 STAT_USM_STATS_START = STAT_USMSTATSUNSUPPORTEDSECLEVELS STAT_USM_STATS_END = STAT_USMSTATSDECRYPTIONERRORS STAT_SNMPINPKTS = 9 STAT_SNMPOUTPKTS = 10 STAT_SNMPINBADVERSIONS = 11 STAT_SNMPINBADCOMMUNITYNAMES = 12 STAT_SNMPINBADCOMMUNITYUSES = 13 STAT_SNMPINASNPARSEERRS = 14 STAT_SNMPINTOOBIGS = 16 STAT_SNMPINNOSUCHNAMES = 17 STAT_SNMPINBADVALUES = 18 STAT_SNMPINREADONLYS = 19 STAT_SNMPINGENERRS = 20 STAT_SNMPINTOTALREQVARS = 21 STAT_SNMPINTOTALSETVARS = 22 STAT_SNMPINGETREQUESTS = 23 STAT_SNMPINGETNEXTS = 24 STAT_SNMPINSETREQUESTS = 25 STAT_SNMPINGETRESPONSES = 26 STAT_SNMPINTRAPS = 27 STAT_SNMPOUTTOOBIGS = 28 STAT_SNMPOUTNOSUCHNAMES = 29 STAT_SNMPOUTBADVALUES = 30 STAT_SNMPOUTGENERRS = 32 STAT_SNMPOUTGETREQUESTS = 33 STAT_SNMPOUTGETNEXTS = 34 STAT_SNMPOUTSETREQUESTS = 35 STAT_SNMPOUTGETRESPONSES = 36 STAT_SNMPOUTTRAPS = 37 STAT_SNMPSILENTDROPS = 39 STAT_SNMPPROXYDROPS = 40 STAT_SNMP_STATS_START = STAT_SNMPINPKTS STAT_SNMP_STATS_END = STAT_SNMPPROXYDROPS STAT_SNMPUNAVAILABLECONTEXTS = 41 STAT_SNMPUNKNOWNCONTEXTS = 42 STAT_TARGET_STATS_START = STAT_SNMPUNAVAILABLECONTEXTS STAT_TARGET_STATS_END = STAT_SNMPUNKNOWNCONTEXTS MAX_STATS = 43 COMMUNITY_MAX_LEN = 256 SPRINT_MAX_LEN = 2560 NULL = 0 TRUE = 1 FALSE = 0 READ = 1 WRITE = 0 RESERVE1 = 0 RESERVE2 = 1 ACTION = 2 COMMIT = 3 FREE = 4 UNDO = 5 FINISHED_SUCCESS = 9 FINISHED_FAILURE = 10 RONLY = 0x1 RWRITE = 0x2 NOACCESS = 0x0000 ASN_IPADDRESS = (ASN_APPLICATION | 0) ASN_COUNTER = (ASN_APPLICATION | 1) ASN_GAUGE = (ASN_APPLICATION | 2) ASN_UNSIGNED = (ASN_APPLICATION | 2) ASN_TIMETICKS = (ASN_APPLICATION | 3) ASN_OPAQUE = (ASN_APPLICATION | 4) ASN_NSAP = (ASN_APPLICATION | 5) ASN_COUNTER64 = (ASN_APPLICATION | 6) ASN_UINTEGER = (ASN_APPLICATION | 7) ASN_FLOAT = (ASN_APPLICATION | 8) ASN_DOUBLE = (ASN_APPLICATION | 9) ASN_INTEGER64 = (ASN_APPLICATION | 10) ASN_UNSIGNED64 = (ASN_APPLICATION | 11) FIRST_PASS = 1 LAST_PASS = 2 LOG_EMERG = 0 LOG_ALERT = 1 LOG_CRIT = 2 LOG_ERR = 3 LOG_WARNING = 4 LOG_NOTICE = 5 LOG_INFO = 6 LOG_DEBUG = 7 DEFAULT_LOG_ID = "net-snmp" NETSNMP_LOGHANDLER_STDOUT = 1 NETSNMP_LOGHANDLER_STDERR = 2 NETSNMP_LOGHANDLER_FILE = 3 NETSNMP_LOGHANDLER_SYSLOG = 4 NETSNMP_LOGHANDLER_CALLBACK = 5 NETSNMP_LOGHANDLER_NONE = 6 pynetsnmp-0.28.14/COPYRIGHT.txt000644 000765 000765 00000000527 11330646327 015767 0ustar00chetchet000000 000000 All files in this directory and below are: Copyright (c) 2007 Zenoss, Inc. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. For complete information please visit: http://www.zenoss.com/oss/ pynetsnmp-0.28.14/LICENSE.txt000644 000765 000765 00000035452 11330646327 015506 0ustar00chetchet000000 000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS pynetsnmp-0.28.14/SnmpSession.py000644 000765 000765 00000002675 11330646327 016517 0ustar00chetchet000000 000000 __doc__ = "Backwards compatible API for SnmpSession" import netsnmp from ctypes import * class SnmpSession(object): def __init__(self, ip, port=161, timeout=2, retries=2, cmdLineArgs=()): self.ip = ip self.port = port self.timeout = timeout self.retries = retries self.community = "public" self._version = netsnmp.SNMP_VERSION_1 self.cmdLineArgs = cmdLineArgs def setVersion(self, version): if version.find('2') >= 0: self._version = netsnmp.SNMP_VERSION_2c else: self._version = netsnmp.SNMP_VERSION_1 def get(self, oid): "Synchronous get implementation" self.session = netsnmp.Session( version=self._version, timeout=int(self.timeout*1e6), retries=int(self.retries-1), peername= '%s:%d' % (self.ip, self.port), community=self.community, community_len=len(self.community), cmdLineArgs=self.cmdLineArgs ) oid = tuple(map(int, oid.strip('.').split('.'))) self.session.open() try: return self.session.sget([oid]) finally: self.session.close() if __name__ == '__main__': session = SnmpSession('127.0.0.1', timeout=1.5, port=161) session.community = 'public' print session.get('.1.3.6.1.2.1.1.5.0') session.community = 'xyzzy' print session.get('.1.3.6.1.2.1.1.5.0') pynetsnmp-0.28.14/__init__.py000644 000765 000765 00000000066 11330646327 015765 0ustar00chetchet000000 000000 __doc__ = "pynetsnmp is a ctypes wrapper of net-snmp" pynetsnmp-0.28.14/genconstants.py000644 000765 000765 00000002563 11330646327 016740 0ustar00chetchet000000 000000 import re import os def process(f, output): lines = open('/usr/include/net-snmp/library/%s.h' % f).readlines() sp = '[ \t]*' comment = re.compile('/\\*(.*\\*/|[^*]*$)') define = re.compile(sp.join(['^', '#', 'define', '([A-Za-z0-9_]+)', '([^\\\\]+)$'])) junk = ['usm', '(x)', 'sizeof', '(string)', '(byte)', '{', '?', 'err'] for line in lines: line = comment.sub('', line) m = define.match(line) if m: value = m.group(2).strip() value = value.replace('(u_char)', '') if value: for j in junk: if value.find(j) > -1: break else: output.write('%s = %s\n' % (m.group(1), value)) def make_imports(): try: out = open('CONSTANTS.py.new', 'w') out.write("USM_LENGTH_OID_TRANSFORM = 10\n") out.write("NULL = None\n") for f in 'callback asn1 snmp snmp_api snmp_impl snmp_logging'.split(): process(f, out) out.close() os.rename('CONSTANTS.py.new', 'CONSTANTS.py') except IOError: # file not found, prolly pass if __name__=='__main__': from CONSTANTS import * # check the result pynetsnmp-0.28.14/netsnmp.py000644 000765 000765 00000041605 11330646327 015716 0ustar00chetchet000000 000000 import os from ctypes import * from ctypes.util import find_library from CONSTANTS import * # freebsd cannot manage a decent find_library import sys if sys.platform.find('free') > -1: find_library_orig = find_library def find_library(name): for name in ['/usr/lib/lib%s.so' % name, '/usr/local/lib/lib%s.so' % name]: if os.path.exists(name): return name return find_library_orig(name) find_library_orig = find_library def find_library(name): if sys.platform == "darwin": libPath = os.environ.get('DYLD_LIBRARY_PATH', '') else: libPath = os.environ.get('LD_LIBRARY_PATH', '') libPathList = libPath.split(':') for path in libPathList: pathName = path+'/lib%s.so' % name if os.path.exists(pathName): return pathName return find_library_orig(name) import logging log = logging.getLogger('netsnmp') c_int_p = c_void_p authenticator = CFUNCTYPE(c_char_p, c_int_p, c_char_p, c_int) try: # needed by newer netsnmp's crypto = CDLL(find_library('crypto'), RTLD_GLOBAL) except Exception: import warnings warnings.warn("Unable to load crypto library") lib = CDLL(find_library('netsnmp'), RTLD_GLOBAL) lib.netsnmp_get_version.restype = c_char_p oid = c_long u_long = c_ulong u_short = c_ushort u_char_p = c_char_p u_int = c_uint size_t = c_size_t u_char = c_byte class netsnmp_session(Structure): pass class netsnmp_pdu(Structure): pass class netsnmp_transport(Structure): pass # int (*netsnmp_callback) (int, netsnmp_session *, int, netsnmp_pdu *, void *); netsnmp_callback = CFUNCTYPE(c_int, c_int, POINTER(netsnmp_session), c_int, POINTER(netsnmp_pdu), c_void_p) # int (*proc)(int, char * const *, int) arg_parse_proc = CFUNCTYPE(c_int, POINTER(c_char_p), c_int); version = lib.netsnmp_get_version() float_version = float('.'.join(version.split('.')[:2])) localname = [] paramName = [] if float_version < 5.099: raise ImportError("netsnmp version 5.1 or greater is required") if float_version > 5.199: localname = [('localname', c_char_p)] if float_version > 5.299: paramName = [('paramName', c_char_p)] netsnmp_session._fields_ = [ ('version', c_long), ('retries', c_int), ('timeout', c_long), ('flags', u_long), ('subsession', POINTER(netsnmp_session)), ('next', POINTER(netsnmp_session)), ('peername', c_char_p), ('remote_port', u_short), ] + localname + [ ('local_port', u_short), ('authenticator', authenticator), ('callback', netsnmp_callback), ('callback_magic', c_void_p), ('s_errno', c_int), ('s_snmp_errno', c_int), ('sessid', c_long), ('community', u_char_p), ('community_len', size_t), ('rcvMsgMaxSize', size_t), ('sndMsgMaxSize', size_t), ('isAuthoritative', u_char), ('contextEngineID', u_char_p), ('contextEngineIDLen', size_t), ('engineBoots', u_int), ('engineTime', u_int), ('contextName', c_char_p), ('contextNameLen', size_t), ('securityEngineID', u_char_p), ('securityEngineIDLen', size_t), ('securityName', c_char_p), ('securityNameLen', size_t), ('securityAuthProto', POINTER(oid)), ('securityAuthProtoLen', size_t), ('securityAuthKey', u_char * USM_AUTH_KU_LEN), ('securityAuthKeyLen', c_size_t), ('securityAuthLocalKey', c_char_p), ('securityAuthLocalKeyLen', c_size_t), ('securityPrivProto', POINTER(oid)), ('securityPrivProtoLen', c_size_t), ('securityPrivKey', c_char * USM_PRIV_KU_LEN), ('securityPrivKeyLen', c_size_t), ('securityPrivLocalKey', c_char_p), ('securityPrivLocalKeyLen', c_size_t), ] + paramName + [ ('securityModel', c_int), ('securityLevel', c_int), ('securityInfo', c_void_p), ('myvoid', c_void_p), ] dataFreeHook = CFUNCTYPE(c_void_p) class counter64(Structure): _fields_ = [ ('high', c_ulong), ('low', c_ulong), ] class netsnmp_vardata(Union): _fields_ = [ ('integer', POINTER(c_long)), ('uinteger', POINTER(c_ulong)), ('string', c_char_p), ('objid', POINTER(oid)), ('bitstring', POINTER(c_ubyte)), ('counter64', POINTER(counter64)), ('floatVal', POINTER(c_float)), ('doubleVal', POINTER(c_double)), ] class netsnmp_variable_list(Structure): pass netsnmp_variable_list._fields_ = [ ('next_variable', POINTER(netsnmp_variable_list)), ('name', POINTER(oid)), ('name_length', c_size_t), ('type', c_char), ('val', netsnmp_vardata), ('val_len', c_size_t), ('name_loc', oid * MAX_OID_LEN), ('buf', c_char * 40), ('data', c_void_p), ('dataFreeHook', dataFreeHook), ('index', c_int), ] netsnmp_pdu._fields_ = [ ('version', c_long ), ('command', c_int ), ('reqid', c_long ), ('msgid', c_long ), ('transid', c_long ), ('sessid', c_long ), ('errstat', c_long ), ('errindex', c_long ), ('time', c_ulong ), ('flags', c_ulong ), ('securityModel', c_int ), ('securityLevel', c_int ), ('msgParseModel', c_int ), ('transport_data', c_void_p), ('transport_data_length', c_int ), ('tDomain', POINTER(oid)), ('tDomainLen', c_size_t ), ('variables', POINTER(netsnmp_variable_list)), ('community', c_char_p), ('community_len', c_size_t ), ('enterprise', POINTER(oid)), ('enterprise_length', c_size_t ), ('trap_type', c_long ), ('specific_type', c_long ), ('agent_addr', c_ubyte * 4), ('contextEngineID', c_char_p ), ('contextEngineIDLen', c_size_t ), ('contextName', c_char_p), ('contextNameLen', c_size_t ), ('securityEngineID', c_char_p), ('securityEngineIDLen', c_size_t ), ('securityName', c_char_p), ('securityNameLen', c_size_t ), ('priority', c_int ), ('range_subid', c_int ), ('securityStateRef', c_void_p), ] netsnmp_pdu_p = POINTER(netsnmp_pdu) # Redirect netsnmp logging to our log class netsnmp_log_message(Structure): pass netsnmp_log_message_p = POINTER(netsnmp_log_message) log_callback = CFUNCTYPE(c_int, c_int, netsnmp_log_message_p, c_void_p); netsnmp_log_message._fields_ = [ ('priority', c_int), ('msg', c_char_p), ] PRIORITY_MAP = { LOG_EMERG : logging.CRITICAL + 2, LOG_ALERT : logging.CRITICAL + 1, LOG_CRIT : logging.CRITICAL, LOG_ERR : logging.ERROR, LOG_WARNING : logging.WARNING, LOG_NOTICE : logging.INFO + 1, LOG_INFO : logging.INFO, LOG_DEBUG : logging.DEBUG, } def netsnmp_logger(a, b, msg): msg = cast(msg, netsnmp_log_message_p) priority = PRIORITY_MAP.get(msg.contents.priority, logging.WARNING) log.log(priority, str(msg.contents.msg).strip()) return 0 netsnmp_logger = log_callback(netsnmp_logger) lib.snmp_register_callback(SNMP_CALLBACK_LIBRARY, SNMP_CALLBACK_LOGGING, netsnmp_logger, 0) lib.netsnmp_register_loghandler(NETSNMP_LOGHANDLER_CALLBACK, LOG_DEBUG) lib.snmp_pdu_create.restype = netsnmp_pdu_p lib.snmp_open.restype = POINTER(netsnmp_session) netsnmp_transport._fields_ = [ ('domain', POINTER(oid)), ('domain_length', c_int), ('local', u_char_p), ('local_length', c_int), ('remote', u_char_p), ('remote_length', c_int), ('sock', c_int), ('flags', u_int), ('data', c_void_p), ('data_length', c_int), ('msgMaxSize', c_size_t), ('f_recv', c_void_p), ('f_send', c_void_p), ('f_close', c_void_p), ('f_accept', c_void_p), ('f_fmtaddr', c_void_p), ] lib.netsnmp_tdomain_transport.restype = POINTER(netsnmp_transport) # int snmp_input(int, netsnmp_session *, int, netsnmp_pdu *, void *); snmp_input_t = CFUNCTYPE(c_int, c_int, POINTER(netsnmp_session), c_int, netsnmp_pdu_p, c_void_p) class UnknownType(Exception): pass def mkoid(n): oids = (oid * len(n))() for i, v in enumerate(n): oids[i] = v return oids def decodeOid(pdu): return tuple([pdu.val.objid[i] for i in range(pdu.val_len / sizeof(u_long))]) def decodeIp(pdu): return '.'.join(map(str, pdu.val.bitstring[:4])) def decodeBigInt(pdu): int64 = pdu.val.counter64.contents return (int64.high << 32L) + int64.low def decodeString(pdu): if pdu.val_len: return string_at(pdu.val.bitstring, pdu.val_len) return '' decoder = { chr(ASN_OCTET_STR): decodeString, # chr(ASN_BOOLEAN): lambda pdu: pdu.val.integer.contents.value, chr(ASN_INTEGER): lambda pdu: pdu.val.integer.contents.value, chr(ASN_NULL): lambda pdu: None, chr(ASN_OBJECT_ID): decodeOid, chr(ASN_BIT_STR): decodeString, chr(ASN_IPADDRESS): decodeIp, chr(ASN_COUNTER): lambda pdu: pdu.val.uinteger.contents.value, chr(ASN_GAUGE): lambda pdu: pdu.val.uinteger.contents.value, chr(ASN_TIMETICKS): lambda pdu: pdu.val.uinteger.contents.value, chr(ASN_COUNTER64): decodeBigInt, chr(ASN_APP_FLOAT): lambda pdu: pdu.val.float.contents.value, chr(ASN_APP_DOUBLE): lambda pdu: pdu.val.double.contents.value, } def decodeType(var): oid = [var.name[i] for i in range(var.name_length)] decode = decoder.get(var.type, None) if not decode: # raise UnknownType(oid, ord(var.type)) return (oid, None) return oid, decode(var) def getResult(pdu): result = [] var = pdu.variables while var: var = var.contents oid, val = decodeType(var) result.append( (tuple(oid), val) ) var = var.next_variable return result class SnmpError(Exception): def __init__(self, why): lib.snmp_perror(why) Exception.__init__(self, why) sessionMap = {} def _callback(operation, sp, reqid, pdu, magic): sess = sessionMap[magic] try: if operation == NETSNMP_CALLBACK_OP_RECEIVED_MESSAGE: sess.callback(pdu.contents) elif operation == NETSNMP_CALLBACK_OP_TIMED_OUT: sess.timeout(reqid) else: log.error("Unknown operation: %d", operation) except Exception, ex: log.exception("Exception in _callback %s", ex) return 1 _callback = netsnmp_callback(_callback) class ArgumentParseError(Exception): pass class TransportError(Exception): pass def _doNothingProc(argc, argv, arg): return 0 _doNothingProc = arg_parse_proc(_doNothingProc) def parse_args(args, session): import sys args = [sys.argv[0],] + args argc = len(args) argv = (c_char_p * argc)() for i in range(argc): # snmp_parse_args mutates argv, so create a copy argv[i] = create_string_buffer(args[i]).raw if lib.snmp_parse_args(argc, argv, session, '', _doNothingProc) < 0: def toList(args): return [str(x) for x in args] raise ArgumentParseError("Unable to parse arguments", toList(argv)) # keep a reference to the args for as long as sess is alive return argv def initialize_session(sess, cmdLineArgs, kw): args = None kw = kw.copy() if cmdLineArgs: cmdLine = [x for x in cmdLineArgs] if type(cmdLine[0]) == type(()): result = [] for opt, val in cmdLine: result.append(opt) result.append(val) cmdLine = result if kw.get('peername'): cmdLine.append(kw['peername']) del kw['peername'] args = parse_args(cmdLine, byref(sess)) for attr, value in kw.items(): setattr(sess, attr, value) return args class Session(object): cb = None def __init__(self, cmdLineArgs = (), **kw): self.cmdLineArgs = cmdLineArgs self.kw = kw self.sess = None self.args = None def open(self): sess = netsnmp_session() lib.snmp_sess_init(byref(sess)) self.args = initialize_session(sess, self.cmdLineArgs, self.kw) sess.callback = _callback sess.callback_magic = id(self) sess = lib.snmp_open(byref(sess)) self.sess = sess # cast(sess, POINTER(netsnmp_session)) if not self.sess: raise SnmpError('snmp_open') sessionMap[id(self)] = self def awaitTraps(self, peername, fileno = -1): lib.netsnmp_udp_ctor() transport = lib.netsnmp_tdomain_transport(peername, 1, "udp") if not transport: raise SnmpError("Unable to create transport", peername) if fileno >= 0: os.dup2(fileno, transport.contents.sock) sess = netsnmp_session() lib.snmp_sess_init(byref(sess)) self.sess = addressof(sess) sess.peername = SNMP_DEFAULT_PEERNAME sess.version = SNMP_DEFAULT_VERSION sess.community_len = SNMP_DEFAULT_COMMUNITY_LEN sess.retries = SNMP_DEFAULT_RETRIES sess.timeout = SNMP_DEFAULT_TIMEOUT sess.callback = _callback sess.callback_magic = id(self) # sess.authenticator = None sess.isAuthoritative = SNMP_SESS_UNKNOWNAUTH rc = lib.snmp_add(self.sess, transport, None, None) if not rc: raise SnmpError('snmp_add') sessionMap[id(self)] = self def close(self): if not self.sess: return if id(self) not in sessionMap: log.warn("Unable to find session id %r in sessionMap", self.kw) return lib.snmp_close(self.sess) del sessionMap[id(self)] self.args = None def callback(self, pdu): pass def timeout(self, reqid): pass def _create_request(self, packetType): return lib.snmp_pdu_create(packetType) def sget(self, oids): req = self._create_request(SNMP_MSG_GET) for oid in oids: oid = mkoid(oid) lib.snmp_add_null_var(req, oid, len(oid)) response = netsnmp_pdu_p() if lib.snmp_synch_response(self.sess, req, byref(response)) == 0: result = dict(getResult(response.contents)) lib.snmp_free_pdu(response) return result def get(self, oids): req = self._create_request(SNMP_MSG_GET) for oid in oids: oid = mkoid(oid) lib.snmp_add_null_var(req, oid, len(oid)) if not lib.snmp_send(self.sess, req): lib.snmp_free_pdu(req) raise SnmpError("snmp_send") return req.contents.reqid def getbulk(self, nonrepeaters, maxrepetitions, oids): req = self._create_request(SNMP_MSG_GETBULK) req = cast(req, POINTER(netsnmp_pdu)) req.contents.errstat = nonrepeaters req.contents.errindex = maxrepetitions for oid in oids: oid = mkoid(oid) lib.snmp_add_null_var(req, oid, len(oid)) if not lib.snmp_send(self.sess, req): lib.snmp_free_pdu(req) raise SnmpError("snmp_send") return req.contents.reqid def walk(self, root): req = self._create_request(SNMP_MSG_GETNEXT) oid = mkoid(root) lib.snmp_add_null_var(req, oid, len(oid)) if not lib.snmp_send(self.sess, req): lib.snmp_free_pdu(req) raise SnmpError("snmp_send") return req.contents.reqid MAXFD = 1024 fdset = c_int32 * (MAXFD/32) class timeval(Structure): _fields_ = [ ('tv_sec', c_long), ('tv_usec', c_long), ] def fdset2list(rd, n): result = [] for i in range(len(rd)): if rd[i]: for j in range(0, 32): bit = 0x00000001 << (j % 32) if rd[i] & bit: result.append(i * 32 + j) return result def snmp_select_info(): rd = fdset() maxfd = c_int(0) timeout = timeval() timeout.tv_sec = 1 timeout.tv_usec = 0 block = c_int(0) maxfd = c_int(MAXFD) lib.snmp_select_info(byref(maxfd), byref(rd), byref(timeout), byref(block)) t = None if not block: t = timeout.tv_sec + timeout.tv_usec / 1e6 return fdset2list(rd, maxfd.value), t def snmp_read(fd): rd = fdset() rd[fd / 32] |= 1 << (fd % 32) lib.snmp_read(byref(rd)) done = False def loop(): while not done: from select import select rd, t = snmp_select_info() if t is None: break rd, w, x = select(rd, [], [], t) if rd: for r in rd: snmp_read(r) else: lib.snmp_timeout() def stop(): global done done = 1 pynetsnmp-0.28.14/pkg000755 000765 000765 00000002125 11330646327 014361 0ustar00chetchet000000 000000 #! /bin/sh # # Script used by the Zenoss Dev team (the authors of pynetsnmp) to # release and deploy updated versions. First, go edit setup.py # and update the VERSION value. # # Run this script. This will generate a tarball in the parent # directory (..). Move this script to your zenoss inst/externallibs # directory and remove the old tarball and add the new one: # # $ svn remove pynetsnmp-OLDVERSION.tar.gz # $ svn add pynetsnmp-NEWVERSION.tar.gz # # Then you are set to re-release Zenoss. # quit() { echo $@ exit 1 } PACKAGE=pynetsnmp VERSION=`python -c 'import version; print version.VERSION'` VPACKAGE=$PACKAGE-$VERSION SVN=http://dev.zenoss.org/svn SVNTRUNK=$SVN/trunk/$PACKAGE SVNTAG=$SVN/tags/$VPACKAGE svn cp -m"making release $VERSION" $SVNTRUNK $SVNTAG || quit cannot create tag svn export $SVNTAG /tmp/$VPACKAGE || quit cannot create export tree OLD=`pwd` ( cd /tmp tar -czvf $OLD/../$VPACKAGE.tar.gz $VPACKAGE rm -rf $VPACKAGE ) || quit cannot create tarball echo "Remember to move ../$VPACKAGE.tar.gz the Zenoss " echo "inst/externallibs directory and check it in." exit 0 pynetsnmp-0.28.14/setup.py000644 000765 000765 00000002003 11330646327 015357 0ustar00chetchet000000 000000 from distutils.command.build import build as _build from distutils.command.clean import clean as _clean from distutils.core import setup import os import genconstants from version import VERSION class clean(_clean): def run(self): if os.path.exists('/usr/include/net-snmp/library/snmp_api.h'): for filename in "CONSTANTS.py", "CONSTANTS.pyc": if os.path.exists(filename): os.remove(filename) _clean.run(self) class build(_build): def run(self): if os.path.exists('/usr/include/net-snmp/library/snmp_api.h'): genconstants.make_imports() _build.run(self) if __name__=='__main__': setup(name='pynetsnmp', version=VERSION, description='ctypes wrapper for net-snmp', author='Eric C. Newton', author_email='ecn@zenoss.com', cmdclass={'build': build, 'clean' : clean}, package_dir = {'pynetsnmp':'.',}, packages = ['pynetsnmp',], ) pynetsnmp-0.28.14/tableretriever.py000644 000765 000765 00000004551 11330646327 017250 0ustar00chetchet000000 000000 from twisted.internet import defer from twistedsnmp import asOidStr, asOid class _TableStatus(object): def __init__(self, startOidStr): self.startOidStr = startOidStr self.startOid = asOid(startOidStr) self.result = [] self.finished = False class TableRetriever(object): def __init__(self, proxy, oids, timeout = 1.5, retryCount = 3, maxRepetitions = 100, limit = 1000): self.proxy = proxy self.tableStatus = [_TableStatus(oid) for oid in oids] self.defer = defer.Deferred() if proxy.snmpVersion.find('1') > -1: self.how = proxy._walk else: def v2v3how(oids): return proxy._getbulk(0, min(maxRepetitions, limit), [oids]) self.how = v2v3how self.limit = limit self.count = 0 self.hit_limit = False def __call__(self): self.fetchSomeMore() return self.defer def fetchSomeMore(self): for ts in self.tableStatus: if ts.finished: continue if ts.result: lastOid = ts.result[-1][0] else: lastOid = ts.startOid d = self.how(lastOid) d.addCallback(self.saveResults, ts) d.addErrback(self.error) return results = {} for ts in self.tableStatus: results[ts.startOidStr]=dict([(asOidStr(oid), value) for oid, value in ts.result]) self.defer.callback(results) self.defer = None def saveResults(self, values, ts): if values: for oid, value in values: self.count += 1 if oid[:len(ts.startOid)]==ts.startOid and oid > ts.startOid: # defend against going backwards if ts.result and oid<=ts.result[-1][0]: ts.finished = True else: ts.result.append((oid, value)) else: ts.finished = True else: ts.finished = True if not ts.finished and self.count >= self.limit: ts.finished = True self.hit_limit = True self.fetchSomeMore() def error(self, why): self.defer.errback(why) self.defer = None pynetsnmp-0.28.14/test/000755 000765 000765 00000000000 11330646327 014631 5ustar00chetchet000000 000000 pynetsnmp-0.28.14/._twistedsnmp.py000644 000765 000765 00000000273 11330646327 017024 0ustar00chetchet000000 000000 Mac OS X  2ATTR##com.macromates.caret{ column = 0; line = 152; }pynetsnmp-0.28.14/twistedsnmp.py000644 000765 000765 00000020100 11330646327 016576 0ustar00chetchet000000 000000 import netsnmp from CONSTANTS import * from twisted.internet import reactor from twisted.internet.error import TimeoutError from twisted.internet.interfaces import IReadDescriptor from twisted.python import failure from twisted.internet import defer from sets import Set import logging log = logging.getLogger('twistedsnmp') class Timer(object): callLater = None timer = Timer() fdMap = {} PDU_ERRORS = { SNMP_ERR_NOERROR: "We have no problems here", SNMP_ERR_TOOBIG: "Packet too big", SNMP_ERR_NOSUCHNAME: "Unknown oid", SNMP_ERR_BADVALUE: "Bad value", SNMP_ERR_READONLY: "Oid is read-only", SNMP_ERR_GENERR: "General error", SNMP_ERR_NOACCESS: "Permission denied", SNMP_ERR_WRONGTYPE: "Wrong type", SNMP_ERR_WRONGLENGTH: "Bad length", SNMP_ERR_WRONGENCODING: "Bad encoding", SNMP_ERR_WRONGVALUE: "Bad value", SNMP_ERR_NOCREATION: "No creation", SNMP_ERR_INCONSISTENTVALUE: "Inconsistent value", SNMP_ERR_RESOURCEUNAVAILABLE: "Resource unavailable", SNMP_ERR_COMMITFAILED: "Commit failed", SNMP_ERR_UNDOFAILED: "Undo failed", SNMP_ERR_AUTHORIZATIONERROR: "Authorization error", SNMP_ERR_NOTWRITABLE: "Not writable", SNMP_ERR_INCONSISTENTNAME: "Inconsistent name", } def checkTimeouts(): "Handle timeouts for Net-SNMP" timer.callLater = None netsnmp.lib.snmp_timeout() updateReactor() class SnmpReader: #(IReadDescriptor): "Respond to input events" def logPrefix(self): return 'SnmpReader' def __init__(self, fd): self.fd = fd def doRead(self): netsnmp.snmp_read(self.fd) # updateReactor() def fileno(self): return self.fd def connectionLost(self, why): del fdMap[self.fd] def updateReactor(): "Add/remove event handlers for SNMP file descriptors and timers" fds, t = netsnmp.snmp_select_info() log.debug('reactor settings: %r, %r', fds, t) for fd in fds: if fd not in fdMap: reader = SnmpReader(fd) fdMap[fd] = reader reactor.addReader(reader) current = Set(fdMap.keys()) need = Set(fds) doomed = current - need for d in doomed: reactor.removeReader(fdMap[d]) del fdMap[d] if timer.callLater: timer.callLater.cancel() timer.callLater = None if t is not None: timer.callLater = reactor.callLater(t, checkTimeouts) class SnmpError(Exception): pass class SnmpNameError(Exception): def __init__(self, oid): Exception.__init__(self, 'Bad Name', oid) def asOidStr(oid): """converts an oid int sequence to an oid string""" return '.'+'.'.join([str(x) for x in oid]) def asOid(oidStr): """converts an OID string into a tuple of integers""" return tuple([int(x) for x in oidStr.strip('.').split('.')]) class AgentProxy(object): """The public methods on AgentProxy (get, walk, getbulk) expect input OIDs to be strings, and the result they produce is a dictionary. The dictionary keys are OID strings and the values are the values returned by the SNMP requests. The private methods (_get, _walk, _getbulk) expect input OIDs to be tuples of integers. These methods generate a result that is a list of pairs, each pair consisting of the OID string and the value that is returned by the SNMP query. The list is ordered correctly by the OID (i.e. it is not ordered by the OID string).""" def __init__(self, ip, port=161, community='public', snmpVersion = '1', protocol=None, allowCache = False, timeout = 1.5, tries = 3, cmdLineArgs = ()): self.ip = ip self.port = port self.community = community self.snmpVersion = snmpVersion self.timeout = timeout self.tries = tries self.cmdLineArgs = cmdLineArgs self.defers = {} self.session = None self.return_dct = False def callback(self, pdu): """netsnmp session callback""" result = [] response = netsnmp.getResult(pdu) try: d = self.defers.pop(pdu.reqid) except KeyError: # We seem to end up here if we use bad credentials with authPriv. # The only reasonable thing to do is call all of the deferreds with # no results. for d in (d for d in self.defers.values() if not d.called): reactor.callLater(0, d.callback, result) return for oid, value in response: if self.return_dct: oid = asOidStr(oid) if isinstance(value, tuple): value = asOidStr(value) result.append((oid, value)) if pdu.errstat != netsnmp.SNMP_ERR_NOERROR: # fixme: we can do better: use errback m = PDU_ERRORS.get(pdu.errstat, 'Unknown error (%d)' % pdu.errstat) # log.warning("Packet for %s has error: %s", self.ip, m) result = [] if self.return_dct: result = dict(result) self.return_dct = False reactor.callLater(0, d.callback, result) def timeout_(self, reqid): d = self.defers.pop(reqid) reactor.callLater(0, d.errback, failure.Failure(TimeoutError())) def _getCmdLineArgs(self): version = str(self.snmpVersion).lstrip('v') if version == '2': version += 'c' if self.session is not None: self.session.close() self.session = None cmdLineArgs = list(self.cmdLineArgs) + ['-v', str(version), '-c', self.community, '-t', str(self.timeout), '-r', str(self.tries), '%s:%d' % (self.ip, self.port)] return cmdLineArgs def open(self): self.session = netsnmp.Session(cmdLineArgs=self._getCmdLineArgs()) self.session.callback = self.callback self.session.timeout = self.timeout_ self.session.open() updateReactor() def close(self): assert self.session self.session.close() self.session = None updateReactor() def _get(self, oids, timeout=None, retryCount=None): d = defer.Deferred() try: self.defers[self.session.get(oids)] = d except Exception, ex: return defer.fail(ex) updateReactor() return d def _walk(self, oid, timeout=None, retryCount=None): d = defer.Deferred() try: self.defers[self.session.walk(oid)] = d except Exception, ex: return defer.fail(ex) updateReactor() return d def _getbulk(self, nonrepeaters, maxrepititions, oids): d = defer.Deferred() try: self.defers[self.session.getbulk(nonrepeaters, maxrepititions, oids)] = d except Exception, ex: return defer.fail(ex) updateReactor() return d def getTable(self, oids, **kw): from tableretriever import TableRetriever try: t = TableRetriever(self, oids, **kw) except Exception, ex: return defer.fail(ex) updateReactor() return t() def get(self, oidStrs, timeout=None, retryCount=None): self.return_dct = True oids = [asOid(oidStr) for oidStr in oidStrs] return self._get(oids, timeout, retryCount) def walk(self, oidStr, timeout=None, retryCount=None): self.return_dct = True return self._walk(asOid(oidStr), timeout, retryCount) def getbulk(self, nonrepeaters, maxrepititions, oidStrs): self.return_dct = True oids = [asOid(oidStr) for oidStr in oidStrs] return self._getbulk(nonrepeaters, maxrepititions, oids) class _FakeProtocol: protocol = None def port(self): return self snmpprotocol = _FakeProtocol() pynetsnmp-0.28.14/version.py000644 000765 000765 00000000022 11330646327 015703 0ustar00chetchet000000 000000 VERSION='0.28.14' pynetsnmp-0.28.14/test/get.py000644 000765 000765 00000001575 11330646327 015772 0ustar00chetchet000000 000000 import netsnmp import twistedsnmp import sys from twisted.internet import reactor class Getter(netsnmp.Session): def callback(self, pdu): results = netsnmp.getResult(pdu) for oid, value in results: print oid, `value` reactor.stop() def timeout(self, reqid): print "Timeout" reactor.stop() def main(): name = 'localhost' community = 'public' if len(sys.argv) >= 2: name = sys.argv[1] oids = sys.argv[2:] g = Getter(version = netsnmp.SNMP_VERSION_1, peername = name, community = community, community_len = len(community)) oids = [tuple(map(int, oid.strip('.').split('.'))) for oid in oids] g.open() g.get(oids) twistedsnmp.updateReactor() reactor.run() if __name__ == '__main__': import logging logging.basicConfig() main() pynetsnmp-0.28.14/test/getbulk.py000644 000765 000765 00000002511 11330646327 016637 0ustar00chetchet000000 000000 import netsnmp import twistedsnmp import sys from twisted.internet import reactor class Table(netsnmp.Session): root = None max = None def getTable(self, root, max = 40): self.max = max self.root = root self.getbulk(0, self.max, [root]) def stop(self, why): print "stopping: %s" % why if reactor.running: reactor.stop() def callback(self, pdu): results = netsnmp.getResult(pdu) for oid, value in results: if oid[:len(self.root)] != self.root: self.stop("table end") return print '.'.join(map(str, oid)), ':', `value` print if not results: self.stop("empty result") else: self.getbulk(0, self.max, [results[-1][0]]) def timeout(self, reqid): self.stop("Timeout") def main(): name = 'localhost' community = 'public' if len(sys.argv) >= 2: name = sys.argv[1] oid = (1,3,6,1,2,1,25,4,2,1,2) t = Table(version = netsnmp.SNMP_VERSION_2c, peername = name, community = community, community_len = len(community)) t.open() t.getTable(oid) twistedsnmp.updateReactor() reactor.run() if __name__ == '__main__': import logging logging.basicConfig() main() pynetsnmp-0.28.14/test/ifIndex.py000644 000765 000765 00000001375 11330646327 016577 0ustar00chetchet000000 000000 """prints the number of interfaces returned by a walk of ifIndex""" from tableretriever import TableRetriever from twistedsnmp import AgentProxy from twisted.internet import reactor import logging logging.basicConfig() log = logging.getLogger("ifIndex") def error(why): reactor.stop() log.error('%s', why) def success(result): print len(result.values()[0]) reactor.stop() def closer(result, proxy): proxy.close() return result def main(): proxy = AgentProxy('colo3560g', snmpVersion='1', community='zenoss') proxy.open() tr = TableRetriever(proxy, ('.1.3.6.1.2.1.2.2.1.1',)) d = tr() d.addBoth(closer, proxy) d.addCallback(success) d.addErrback(error) reactor.run() if __name__=='__main__': main() pynetsnmp-0.28.14/test/tableget.py000644 000765 000765 00000001507 11330646327 016775 0ustar00chetchet000000 000000 from tableretriever import TableRetriever from twistedsnmp import AgentProxy from twisted.internet import reactor import logging logging.basicConfig() log = logging.getLogger("tableget") def error(why): reactor.stop() log.error('%s', why) def success(result): import pprint pprint.pprint(result) reactor.stop() def closer(result, proxy): proxy.close() return result if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) proxy = AgentProxy('127.0.0.1', snmpVersion='v2') proxy.open() tr = TableRetriever(proxy, # ('.1.3.6.1.2.1.25.4.2.1.2', '.1.3.6.1.2.1.25.4.2.1.4')) ('.1.3.6.1.2.1.1.5', '.1.3.6.1.2.1.25.4.2.1.4')) d = tr() d.addBoth(closer, proxy) d.addCallback(success) d.addErrback(error) reactor.run() pynetsnmp-0.28.14/test/trap.py000644 000765 000765 00000001733 11330646327 016155 0ustar00chetchet000000 000000 import netsnmp from ctypes import * from CONSTANTS import * import twistedsnmp from twisted.internet import reactor, defer def translateOid(oid): import os fp = os.popen('snmptranslate %s' % oid) result = fp.read().strip() fp.close() return result class Trapd(netsnmp.Session): def callback(self, pdu): result = netsnmp.getResult(pdu) print result for oid, value in result: oid = '.'.join(map(str, oid)) print translateOid(oid), value print pdu.command if pdu.command == SNMP_MSG_TRAP: pass elif pdu.command == SNMP_MSG_TRAP2: pass elif pdu.command == SNMP_MSG_INFORM: pass def main(argv): import sys hostPort = argv[1] s = Trapd() s.awaitTraps(hostPort) twistedsnmp.updateReactor() reactor.run() if __name__=='__main__': import sys import logging logging.basicConfig() main(sys.argv) pynetsnmp-0.28.14/test/twistget.py000644 000765 000765 00000001772 11330646327 017064 0ustar00chetchet000000 000000 from twistedsnmp import AgentProxy from twisted.python import failure from twisted.internet import reactor class Bogus(object): pass def printResults(results): if reactor.running: reactor.stop() if isinstance(results, failure.Failure): raise results.value import pprint pprint.pprint(results) return results def close(results, proxy): proxy.close() reactor.callLater(0.1, reactor.stop) def main(): oids = ['.1.3.6.1.2.1.1.1.0', '.1.3.6.1.2.1.1.2.0', '.1.3.6.1.2.1.1.3.0', '.1.3.6.1.2.1.1.4.0', ] proxy = AgentProxy(ip='127.0.0.1', port=161, community='public', snmpVersion = 1, protocol = Bogus(), allowCache = True) proxy.open() d = proxy.get(oids, 1.0, 3) d.addBoth(printResults) d.addCallback(close, proxy) reactor.run() print "end reactor" if __name__ == '__main__': main() pynetsnmp-0.28.14/test/walk.py000644 000765 000765 00000003326 11330646327 016145 0ustar00chetchet000000 000000 import netsnmp import twistedsnmp import sys from twisted.internet import reactor, defer from twisted.python import failure class Walker(netsnmp.Session): lastOid = None def stop(self, why = None): host = self.sess.contents.peername print "stopping: %s %s" % (host, why or '') if not why: self.defer.callback( (host, self.results) ) else: self.defer.errback(Exception('%s on %s' % (why, host))) import gc gc.collect() def callback(self, pdu): results = netsnmp.getResult(pdu) oid, value = results[0] if oid <= self.lastOid: self.stop() else: self.results.append( (oid, value) ) self.lastOid = oid self.walk(oid) def timeout(self, reqid): self.stop("Timeout") def start(self): self.open() self.defer = defer.Deferred() self.results = [] self.walk((1,)) return self.defer def stop(results): for success, values in results: if success: host, values = values print host, len(values) else: print values if reactor.running: reactor.stop() def main(): import getopt # from snmp_parse_args.c opts = 'Y:VhHm:M:O:I:P:D:dv:r:t:c:Z:e:E:n:u:l:x:X:a:A:p:T:-:3:s:S:L:' args, hosts = getopt.getopt(sys.argv[1:], opts) if not hosts: hosts = ['localhost'] d = defer.DeferredList( [Walker(peername=host, cmdLineArgs=args).start() for host in hosts], consumeErrors=True) d.addBoth(stop) twistedsnmp.updateReactor() reactor.run() if __name__ == '__main__': import logging logging.basicConfig() main()