Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto translate for OID into readably string #379

Open
wants to merge 119 commits into
base: master
Choose a base branch
from
Open

Conversation

xssec
Copy link

@xssec xssec commented Sep 22, 2020

Hi,

If there is any documentation for auto translate OID would be nice...

here is the code:
``
#!/usr/bin/env python3
"""
SNMP TRAP and Infor Reciver for SNMP V1,V2c,V3
"""

import argparse, datetime

try:
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp, udp6
from pysnmp.entity.rfc3413 import ntfrcv
from pysnmp.proto.api import v2c
from pysnmp.smi import builder, view, compiler, rfc1902, error
from pysnmp import debug
except ImportError:
print("IMPORT ERROR Please install PYSNMP 4.3.8")

usage: color.fg.green | colors.bg.lightgreen | colors.reset

class colors:
reset='\033[0m'
bold='\033[01m'
disable='\033[02m'
underline='\033[04m'
reverse='\033[07m'
strikethrough='\033[09m'
invisible='\033[08m'
class fg:
black='\033[30m'
red='\033[31m'
green='\033[32m'
orange='\033[33m'
blue='\033[34m'
purple='\033[35m'
cyan='\033[36m'
lightgrey='\033[37m'
darkgrey='\033[90m'
lightred='\033[91m'
lightgreen='\033[92m'
yellow='\033[93m'
lightblue='\033[94m'
pink='\033[95m'
lightcyan='\033[96m'
class bg:
black='\033[40m'
red='\033[41m'
green='\033[42m'
orange='\033[43m'
blue='\033[44m'
purple='\033[45m'
cyan='\033[46m'
lightgrey='\033[47m'

mibViewController = None
pdu_count = 1
MsgReceived = datetime.datetime.now()

def xuser_input(snmpEngine):
"""
TBD
:param snmpEngine:
:return:
"""
CUSTOM_MIB_PATH= '/usr/share/snmp/mibs/'
LOAD_MIB_MODULE = ''
ans = 'yes'
print("\n")
PORT = input("Please Provide The SNMP Trap Port: ")
VERSION = input("Please Enter SNMP Version [OPTION: 1,2,3] : ")
IPversion = input("Please IP Type [OPTION: 4, 6] :")

if VERSION in ['1', '2']:
    COMMUNITYSTRING = input("Please Provide SNMP V1/V2 community String: ")
    config.addV1System(snmpEngine, COMMUNITYSTRING, COMMUNITYSTRING)
    while 1:
        ans = input("Want to add another community (""Yes/No/n/y)?")
        if ans in ["yes", "Yes", "Y", "y"]:
            COMMUNITYSTRING = input("Please Provide SNMP V1/V2 community String: ")
            config.addV1System(snmpEngine, COMMUNITYSTRING, COMMUNITYSTRING)
        else:
            break
else:
    add_snmp_v3(snmpEngine)

_new_mib_path =input("Please provide the custom mib dir path: ")
_new_mib_path = _new_mib_path.strip()

if _new_mib_path and _new_mib_path[-1] == "/":
    CUSTOM_MIB_PATH = _new_mib_path+','+CUSTOM_MIB_PATH
else:
    CUSTOM_MIB_PATH = _new_mib_path+'/'+','+CUSTOM_MIB_PATH
    LOAD_MIB_MODULE = input("Please provide the custom MIB Name seperated by comma: ")
    print("\n")
    return COMMUNITYSTRING, CUSTOM_MIB_PATH, PORT, LOAD_MIB_MODULE, IPversion

def add_transport(snmpEngine, PORT, IPversion):
"""
:param snmpEngine:
:return:
"""
try:

    if IPversion == '6':
        config.addTransport(
                         snmpEngine,
                         udp.domainName,
                         udp6.Udp6SocketTransport().openServerMode(('::', int(PORT)))
                        )
    else:
        config.addTransport(
                         snmpEngine,
                         udp.domainName,
                         udp.UdpTransport().openServerMode(('0.0.0.0', int(PORT)))
                        )
except error.CarrierError as excep:
    print("Port Binding Failed the Provided Port {} is in Use".format(PORT))

def add_snmp_v3(snmpEngine):
"""
TBD
:param snmpEngine:
:return:
"""
__authProtocol = {
'usmHMACMD5AuthProtocol': config.usmHMACMD5AuthProtocol,
'usmHMACSHAAuthProtocol': config.usmHMACSHAAuthProtocol,
'usmAesCfb128Protocol': config.usmAesCfb128Protocol,
'usmAesCfb256Protocol': config.usmAesCfb256Protocol,
'usmAesCfb192Protocol': config.usmAesCfb192Protocol,
'usmDESPrivProtocol': config.usmDESPrivProtocol,
'usmNoAuthProtocol': config.usmNoAuthProtocol,
'usmNoPrivProtocol': config.usmNoPrivProtocol
}
while 1:
V3=input("Want to add New V3 User (Yes/No/n/y)?")
if V3 in ["yes", "Yes", "Y", "y"]:
v3_user = input("Provide V3 User Name: ")
v3_authkey = input("Provide Auth Key: ")
v3_privkey = input("Provide Priv Key: ")
authProtocol = input("Provide authProtocol: Option: ["
"usmNoAuthProtocol, "
"usmHMACMD5AuthProtocol, "
"usmHMACSHAAuthProtocol] :")
privProtocol = input("Provide privProtocol: Option: [""usmNoPrivProtocol, usmDESPrivProtocol, usm3DESEDEPrivProtocol, usmAesCfb128Protocol] :")
securityEngineId = input("Provide V3 security EngineId e.g. ""'800000d30300000e112245' :")
config.addV3User(snmpEngine, userName=v3_user,
authKey=v3_authkey, privKey=v3_privkey,
authProtocol=__authProtocol.get(
authProtocol, config.usmNoAuthProtocol),
privProtocol=__authProtocol.get(
privProtocol,config.usmNoPrivProtocol),
securityEngineId=v2c.OctetString(
hexValue=securityEngineId))
elif V3 in ["No", "n", "N", "no"]:
break
else:
continue

def mib_builder(custom_mib_path, LOAD_MIB_MODULE):
mibBuilder = builder.MibBuilder()
try:
if custom_mib_path:
compiler.addMibCompiler(mibBuilder, sources=custom_mib_path.split(","))
global mibViewController
mibViewController = view.MibViewController(mibBuilder)
if LOAD_MIB_MODULE:
_mibs=LOAD_MIB_MODULE.split(",")
mibBuilder.loadModules(*_mibs)
except error.MibNotFoundError as excep:
print(" {} Mib Not Found!".format(excep))

def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx):
global pdu_count
global mibViewController
print(colors.fg.yellow+"--------------------- NEW Notification(PDU_COUNT: {}) ---------------------".format(pdu_count),colors.reset)
execContext = snmpEngine.observer.getExecutionContext('rfc3412.receiveMessage:request')
print(colors.fg.yellow+ "#MsgReceived: %s" %MsgReceived, colors.reset)
print(colors.fg.lightgrey +'#Notification from %s \n#ContextEngineId: "%s" \n#ContextName: "%s" \n#SNMPVER "%s" \n#SecurityName "%s"' % ('@'.join([str(x) for x in execContext['transportAddress']]),contextEngineId.prettyPrint(),contextName.prettyPrint(), execContext['securityModel'], execContext['securityName']),colors.reset)
for oid, val in varBinds:
output = rfc1902.ObjectType(rfc1902.ObjectIdentity(oid),val).resolveWithMib(mibViewController).prettyPrint()
print(output)
pdu_count +=1

def check_parser():
"""
TBD
:return:
"""
parser = argparse.ArgumentParser()
parser.add_argument("--debug", help="Enable Debug Mode")
args = parser.parse_args()
if args.debug:
debug.setLogger(debug.Debug('all'))

if name == "main":
check_parser()

snmpEngine = engine.SnmpEngine()
COMMUNITYSTRING, CUSTOM_MIB_PATH, PORT, LOAD_MIB_MODULE, IPversion = xuser_input(snmpEngine)
mib_builder(CUSTOM_MIB_PATH, LOAD_MIB_MODULE)
ntfrcv.NotificationReceiver(snmpEngine, cbFun)
add_transport(snmpEngine, PORT, IPversion)
snmpEngine.transportDispatcher.jobStarted(1)
try:
    print(colors.fg.lightgrey +"Trap Listener started .....",colors.reset)
    print ("To Stop Press Ctrl+c")
    print ("\n")
    snmpEngine.transportDispatcher.runDispatcher()
except: #(KeyboardInterrupt, SystemExit):
    #print("SnmpTrap Shutting down...")
    snmpEngine.transportDispatcher.closeDispatcher()
    raise

``

etingof and others added 30 commits April 9, 2018 11:52
* asyncio.async deprecated since 3.4.4
Python 3.7 was just released [1]. This is a small change to
enable support in pysnmp.

[1] https://docs.python.org/3.7/whatsnew/3.7.html

Signed-off-by: Eric Brown <[email protected]>
It appears that Python 3.7 use in Travis-CI is finally fixed. However,
it requires use of xenial distribution and sudo: true.  Those have
now been added to the matrix.

Signed-off-by: Eric Brown <[email protected]>
Probably introduced by commit 2b27b49
…#175)

Otherwise, they are likely to use the system python.
As async is the keyword since Python 3.7, let's use gettattr
built-in function to call async function from asyncio.
Fixed crash caused by incoming SNMPv3 message
requesting SNMPv1/v2c security model
Fixed out-of-scope OIDs possibly leaking at the end of
SNMP table at hlapi `nextCmd` and `bulkCmd` calls when
`lexicographicMode = False`.
To convey parent exception information on re-raise
etingof and others added 29 commits August 4, 2019 12:40
This SNMP engine ID discovery procedure is spread across message
processing and security modules. This is weird!

Anyway, this change moves SNMP message rewriting, associated with
starting out SNMP discovery sequence, to security module. The
motivation is to let security module making the ultimate decision
whether or not SNMP engine discovery is required.

For example, if localized keys are committed directly to the DB,
security module may just use them without engine discovery phase.
This change introduces "wildcard" SNMP engine ID (0x00000000). Right
before deciding on firing up SNMP engine ID discovery and key
localization procedure, originating SNMP engine will check for
the presence of this magical engine ID (5 zeros), if it is present
in LCD along with the user name being used, localized keys from that
entry will be used.

Does this have security implications?
Fixed a regression in SNMPv3 `msgFlag` initialization on
authoritative SNMP engine ID discovery. This bug causes secure
communication with peer SNMP engines to stall at SNMP engine ID
discovery procedure.
Fixes `genErr` handing in Command Responder when mapping MIB
instrumentation exception onto SNMP errors. Prior to this fix,
`genErr` would never be reported back to SNMP manager.
Handles malformed `setuptools.__version__` such as "41.4.0.post20191022"
The later versions introduce streaming decoding
which requires minor adjustments.
- Added `tox` runner with a handful of basic jobs
- Invoke `tox` from `.travis` to reduce test harness
  duplication
- Rework functional tests to run fully locally against
  SNMP simulator instance
Run just one job per Python version in Travis.

Also lower minimal tox requirement.
Can't figure how to run them properly.
@lextm
Copy link

lextm commented Jan 20, 2023

Not sure why you created this. If this is an issue, you should open a new one under Issues.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.