Exemplo n.º 1
0
 def test_snmp(target, port=161, community='public'):
     try:
         errorIndication, errorStatus, errorIndex, varBinds = next(
             getCmd(SnmpEngine(),
                    # mpModel -> 0:v1,1:v2c
                    CommunityData(community, mpModel=1),
                    UdpTransportTarget(
                        (target, int(port)), timeout=1, retries=1),
                    ContextData(),
                    ObjectType(ObjectIdentity(
                        'SNMPv2-MIB', 'sysDescr', 0)),
                    ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysName', 0)))
         )
         if errorIndication:
             return (False, errorIndication)
         elif errorStatus:
             msg = '%s at %s' % (errorStatus.prettyPrint(
             ), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')
             return (False, msg)
         else:
             result = []
             for varBind in varBinds:
                 result.append(' = '.join(
                     [x.prettyPrint() for x in varBind]))
             return (True, result)
     except Exception as e:
         # raise
         return (False, str(e))
Exemplo n.º 2
0
def _create_notification_type(event_context):
    event_type = event_context['event_type']
    workflow_id = event_context['workflow_id']
    execution_id = event_context['execution_id']
    tenant_name = event_context['tenant_name']
    deployment_id = event_context['deployment_id'] or ''
    timestamp = _get_epoch_time(event_context)
    execution_parameters = _get_execution_parameters(event_context)

    notification_type = NotificationType(
        ObjectIdentity(CLOUDIFY_MIB, notification_types[event_type]))
    notification_type.addVarBinds(
        ObjectType(ObjectIdentity(CLOUDIFY_MIB, EXECUTION_ID), execution_id),
        ObjectType(ObjectIdentity(CLOUDIFY_MIB, WORKFLOW_NAME), workflow_id),
        ObjectType(ObjectIdentity(CLOUDIFY_MIB, TENANT_NAME), tenant_name),
        ObjectType(ObjectIdentity(CLOUDIFY_MIB, DEPLOYMENT_ID), deployment_id),
        ObjectType(ObjectIdentity(CLOUDIFY_MIB, TIMESTAMP), timestamp),
        ObjectType(ObjectIdentity(CLOUDIFY_MIB, WORKFLOW_PARAMETERS),
                   execution_parameters))

    if event_type == 'workflow_failed':
        error = _get_error(event_context)
        notification_type.addVarBinds(
            ObjectType(ObjectIdentity(CLOUDIFY_MIB, ERROR), error))
    return notification_type
Exemplo n.º 3
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the SNMP sensor."""
    from pysnmp.hlapi import (getCmd, CommunityData, SnmpEngine,
                              UdpTransportTarget, ContextData, ObjectType,
                              ObjectIdentity)

    host = config.get(CONF_HOST)
    port = config.get(CONF_PORT, DEFAULT_PORT)
    community = config.get(CONF_COMMUNITY, DEFAULT_COMMUNITY)
    baseoid = config.get(CONF_BASEOID)

    errindication, _, _, _ = next(
        getCmd(SnmpEngine(), CommunityData(community, mpModel=0),
               UdpTransportTarget((host, port)), ContextData(),
               ObjectType(ObjectIdentity(baseoid))))

    if errindication:
        _LOGGER.error('Please check the details in the configuration file')
        return False
    else:
        data = SnmpData(host, port, community, baseoid)
        add_devices([
            SnmpSensor(data, config.get('name', DEFAULT_NAME),
                       config.get('unit_of_measurement'))
        ])
Exemplo n.º 4
0
 def snmp_connect(self):
     error_indication, error_status, error_index, var_binds = next(
         getCmd(
             SnmpEngine(), CommunityData('public'),
             UdpTransportTarget((self.entry.get_ip(), 161),
                                timeout=self.entry.get_timeout(161),
                                retries=1), ContextData(),
             ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0')),
             ObjectType(ObjectIdentity('1.3.6.1.2.1.1.6.0'))))
     if error_indication:
         result = -1
     elif error_status:
         result = -1
     else:
         result = "OK"
     return result
Exemplo n.º 5
0
def probe_oper_status(player):
    switch = current_app.config['SWITCHES'][player]
    address = switch['address']
    port = switch['port']
    logger.info("Probing status for player %d on switch %s:%d", player,
                address)
    engine = SnmpEngine()
    auth_data = CommunityData(switch['community'], mpModel=1)
    transport = UdpTransportTarget((address, port))
    interfaces = switch['interfaces']
    oper_states = []
    for chunk in chunked(
        (ObjectType(ObjectIdentity(ifOperStatus.oid + (index, )), Null())
         for index in interfaces), 24):
        cmd = getCmd(engine, auth_data, transport, ContextData(), *chunk)
        errorIndication, errorStatus, errorIndex, varBinds = next(cmd)
        if errorIndication is not None:
            raise Exception("SNMP error returned")
        oper_states.extend(
            ifOperStatus(int(value)) for identity, value in varBinds)
    with StateLock:
        for cell_state, (index,
                         oper_state) in zip(current_app.cell_state[player],
                                            enumerate(oper_states)):
            if oper_state == ifOperStatus.down and cell_state != CellState.EMPTY:
                current_app.cell_state[player][index] = CellState.PRESENT

            if oper_state == ifOperStatus.up and cell_state != CellState.EMPTY:
                current_app.cell_state[player][index] = CellState.HIT
        if not any(cell_state == CellState.PRESENT
                   for cell_state in current_app.cell_state[player]):
            current_app.game_state = GameState.OVER
            return True
    return False
Exemplo n.º 6
0
    def _oid_get(self, oid):
        """
        Performs SNMP get command and returns OID value by sending a SNMP Get message.

        Args:
            oid (str): Full OID identifying the object to be read.

        Return:
            OID value (int)
        """
        errorIndication, errorStatus, errorIndex, varBinds = next(
            getCmd(self._snmp_engine, self._community_data,
                   self._udp_transport_target, self._context,
                   ObjectType(ObjectIdentity(oid))))

        if errorIndication:
            msg = 'Found PDU errorIndication: {}'.format(errorIndication)
            logger.exception(msg)
            raise RuntimeError(msg)
        elif errorStatus:
            msg = 'Found PDU errorStatus: {}'.format(errorStatus)
            logger.exception(msg)
            raise RuntimeError(msg)

        return int(str(varBinds[-1]).partition('= ')[-1])
def define_request(source, ip, community, snmp_version, fileconfname, pathfile,
                   protocol, srvprovision, enableconfstart, urlfirmware,
                   enablereboot):
    if snmp_version == '2c':
        communityData = CommunityData(community, mpModel=1)
    if snmp_version == '1':
        communityData = CommunityData(community, mpModel=0)
    if source:
        assd = AsynsockDispatcher()
        sock_transport = udp.UdpSocketTransport()
        sock_transport.socket.setsockopt(socket.SOL_SOCKET, 25, source + '\0')
        snmp_engine = engine.SnmpEngine()
        assd.registerTransport(udp.domainName, sock_transport)
        snmp_engine.registerTransportDispatcher(assd)
    else:
        snmp_engine = engine.SnmpEngine()
    varBind = []
    result = []
    for errorIndication, errorStatus, errorIndex, varBinds in setCmd(
            snmp_engine, communityData, UdpTransportTarget((ip, 161)),
            ContextData(),
            ObjectType(
                ObjectIdentity(
                    '1.3.6.1.4.1.4935.1000.100.200.100.800.1.100.100.0'),
                OctetString(fileconfname)),
            ObjectType(
                ObjectIdentity(
                    '.1.3.6.1.4.1.4935.1000.100.200.100.800.1.100.300.0'),
                OctetString(pathfile)),
            ObjectType(
                ObjectIdentity(
                    '.1.3.6.1.4.1.4935.1000.100.200.100.800.1.100.400.100.0'),
                Integer32(protocol)),
            ObjectType(
                ObjectIdentity(
                    '.1.3.6.1.4.1.4935.1000.100.200.100.800.1.100.400.400.0'),
                OctetString(srvprovision)),
            ObjectType(
                ObjectIdentity(
                    '.1.3.6.1.4.1.4935.1000.100.200.100.800.1.100.500.100.0'),
                Integer32(enableconfstart)),
            ObjectType(
                ObjectIdentity(
                    '.1.3.6.1.4.1.4935.1000.100.200.100.1300.1.450.0'),
                OctetString(urlfirmware)),
            ObjectType(
                ObjectIdentity(
                    '.1.3.6.1.4.1.4935.1000.100.200.100.1300.1.500.0'),
                Integer32(enablereboot))):
        varBind.append(varBinds)
        for i in varBinds:
            i = str(i)
            i = i.split('=')[1]
            result.append(i)


#             result.append(str(i))
#             varBind = varBind.split('=')[1]
#             result.append(varBind)
    return result
Exemplo n.º 8
0
 def get_pdu(self, message):
     # Properties of the managed object within the device are
     # arranged in this MIB tree structure. the complete path from the
     # top of the tree is ODI
     # Iso(1).org(3).dod(6).internet(1).private(4).2312.19.1.0
     pdu = [
         ObjectType(ObjectIdentity('1.3.6.1.4.2312.19.1.0'),
                    OctetString(message))]
     return pdu
Exemplo n.º 9
0
    def set_outlet_on(self, outlet, on):
        """
        Set an outlet on or off

        :param outlet: Which outlet to set the power for (for my model this is
                       in the range 1 through 8)
        :param on: True means turn it on, False means turn it off
        """
        # OK, sorry for this insane code - the pysnmp docs explicitly say you
        # should just copy paste their examples.
        # This is based on the code from here:
        # http://snmplabs.com/pysnmp/examples/hlapi/asyncore/sync/manager/cmdgen/modifying-variables.html

        # The command we would run to power on outlet 1 on the PDU, if we were
        # not masochists is this:
        #
        # snmpset -v 1 -c private $IPADDR CPS-MIB::ePDUOutletControlOutletCommand.1 i immediateOn
        #
        # However to get those human-readable names to work we'd need to
        # download MIBs and tell pysnmp about them. pysnmp + pysmi apparently
        # know how to do this but I tried to point it at the CyberPower MIB file
        # and it failed silently so huffed and gave up.
        #
        # So instead, we're going to do something more akin to this command,
        # which is exactly the same thing but without the human-readable names:
        #
        # snmpset -v 1 -c private $IPADDR .1.3.6.1.4.1.3808.1.1.3.3.3.1.1.4.2 i 1
        #
        # In that command ".1.3.6.1.4.1.3808.1.1.3.3.3.1.1.4.2" is the
        # masochistic name for "CPS-MIB::ePDUOutletControlOutletCommand.2" and
        # "1" is the masochistic name for "immediateOn"
        #
        # I figured out what that command would be by running this:
        # snmptranslate -On CPS-MIB::ePDUOutletControlOutletCommand
        #
        # SnmpEngine and ContextData are just pointless boilerplate required by
        # pysnmp.  Hopefully you can sort of see how the other bits map to the
        # code below (the "i" becaomse "Integer32").

        oid = ObjectIdentity(
            '1.3.6.1.4.1.3808.1.1.3.3.3.1.1.4.{}'.format(outlet))
        target_state = 'immediateOn' if on else 'immediateOff'
        errorIndication, errorStatus, errorIndex, varBinds = next(
            setCmd(
                SnmpEngine(), CommunityData('private'),
                UdpTransportTarget((self.host, 161)), ContextData(),
                ObjectType(oid,
                           Integer32(self.outlet_state_oids[target_state]))))

        if errorIndication:
            raise CyberPowerPduException(errorIndication)
        elif errorStatus:
            raise CyberPowerPduException(
                '%s at %s' %
                (errorStatus.prettyPrint(),
                 errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))