Esempio n. 1
0
async def async_setup_platform(opp,
                               config,
                               async_add_entities,
                               discovery_info=None):
    """Set up the SNMP sensor."""
    name = config.get(CONF_NAME)
    host = config.get(CONF_HOST)
    port = config.get(CONF_PORT)
    community = config.get(CONF_COMMUNITY)
    baseoid = config.get(CONF_BASEOID)
    unit = config.get(CONF_UNIT_OF_MEASUREMENT)
    version = config.get(CONF_VERSION)
    username = config.get(CONF_USERNAME)
    authkey = config.get(CONF_AUTH_KEY)
    authproto = config.get(CONF_AUTH_PROTOCOL)
    privkey = config.get(CONF_PRIV_KEY)
    privproto = config.get(CONF_PRIV_PROTOCOL)
    accept_errors = config.get(CONF_ACCEPT_ERRORS)
    default_value = config.get(CONF_DEFAULT_VALUE)
    value_template = config.get(CONF_VALUE_TEMPLATE)

    if value_template is not None:
        value_template.opp = opp

    if version == "3":

        if not authkey:
            authproto = "none"
        if not privkey:
            privproto = "none"

        request_args = [
            SnmpEngine(),
            UsmUserData(
                username,
                authKey=authkey or None,
                privKey=privkey or None,
                authProtocol=getattr(hlapi, MAP_AUTH_PROTOCOLS[authproto]),
                privProtocol=getattr(hlapi, MAP_PRIV_PROTOCOLS[privproto]),
            ),
            UdpTransportTarget((host, port)),
            ContextData(),
        ]
    else:
        request_args = [
            SnmpEngine(),
            CommunityData(community, mpModel=SNMP_VERSIONS[version]),
            UdpTransportTarget((host, port)),
            ContextData(),
        ]

    errindication, _, _, _ = await getCmd(*request_args,
                                          ObjectType(ObjectIdentity(baseoid)))

    if errindication and not accept_errors:
        _LOGGER.error("Please check the details in the configuration file")
        return

    data = SnmpData(request_args, baseoid, accept_errors, default_value)
    async_add_entities([SnmpSensor(data, name, unit, value_template)], True)
Esempio n. 2
0
    def __init__(
        self,
        name,
        host,
        port,
        community,
        baseoid,
        commandoid,
        version,
        username,
        authkey,
        authproto,
        privkey,
        privproto,
        payload_on,
        payload_off,
        command_payload_on,
        command_payload_off,
    ):
        """Initialize the switch."""

        self._name = name
        self._baseoid = baseoid

        # Set the command OID to the base OID if command OID is unset
        self._commandoid = commandoid or baseoid
        self._command_payload_on = command_payload_on or payload_on
        self._command_payload_off = command_payload_off or payload_off

        self._state = None
        self._payload_on = payload_on
        self._payload_off = payload_off

        if version == "3":

            if not authkey:
                authproto = "none"
            if not privkey:
                privproto = "none"

            self._request_args = [
                SnmpEngine(),
                UsmUserData(
                    username,
                    authKey=authkey or None,
                    privKey=privkey or None,
                    authProtocol=getattr(hlapi, MAP_AUTH_PROTOCOLS[authproto]),
                    privProtocol=getattr(hlapi, MAP_PRIV_PROTOCOLS[privproto]),
                ),
                UdpTransportTarget((host, port)),
                ContextData(),
            ]
        else:
            self._request_args = [
                SnmpEngine(),
                CommunityData(community, mpModel=SNMP_VERSIONS[version]),
                UdpTransportTarget((host, port)),
                ContextData(),
            ]
Esempio n. 3
0
async def async_setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    async_add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up the SNMP sensor."""
    host = config.get(CONF_HOST)
    port = config.get(CONF_PORT)
    community = config.get(CONF_COMMUNITY)
    baseoid = config.get(CONF_BASEOID)
    version = config[CONF_VERSION]
    username = config.get(CONF_USERNAME)
    authkey = config.get(CONF_AUTH_KEY)
    authproto = config[CONF_AUTH_PROTOCOL]
    privkey = config.get(CONF_PRIV_KEY)
    privproto = config[CONF_PRIV_PROTOCOL]
    accept_errors = config.get(CONF_ACCEPT_ERRORS)
    default_value = config.get(CONF_DEFAULT_VALUE)
    unique_id = config.get(CONF_UNIQUE_ID)

    if version == "3":

        if not authkey:
            authproto = "none"
        if not privkey:
            privproto = "none"

        request_args = [
            SnmpEngine(),
            UsmUserData(
                username,
                authKey=authkey or None,
                privKey=privkey or None,
                authProtocol=getattr(hlapi, MAP_AUTH_PROTOCOLS[authproto]),
                privProtocol=getattr(hlapi, MAP_PRIV_PROTOCOLS[privproto]),
            ),
            UdpTransportTarget((host, port), timeout=DEFAULT_TIMEOUT),
            ContextData(),
        ]
    else:
        request_args = [
            SnmpEngine(),
            CommunityData(community, mpModel=SNMP_VERSIONS[version]),
            UdpTransportTarget((host, port), timeout=DEFAULT_TIMEOUT),
            ContextData(),
        ]

    errindication, _, _, _ = await getCmd(
        *request_args, ObjectType(ObjectIdentity(baseoid))
    )

    if errindication and not accept_errors:
        _LOGGER.error("Please check the details in the configuration file")
        return

    data = SnmpData(request_args, baseoid, accept_errors, default_value)
    async_add_entities([SnmpSensor(hass, data, config, unique_id)], True)
Esempio n. 4
0
 def __init__(self, targets):
     self.requests = []
     self.targets = targets
     self.results = []
     self.community_string = get_config('snmp')['COMM_STRING']
     self.timeout = get_config('snmp')['TIMEOUT']
     self.snmpEngine = SnmpEngine()
     self.mibBuilder = self.snmpEngine.getMibBuilder()
     self.mibViewController = view.MibViewController(self.mibBuilder)
     self.loop = asyncio.get_event_loop()
Esempio n. 5
0
def run_watt(pdu_ip, pdu_node_port):
    snmpEngine = SnmpEngine()
    errorIndication, errorStatus, errorIndex, varBinds = yield from getCmd(
        snmpEngine, CommunityData('public', mpModel=1),
        UdpTransportTarget((pdu_ip, 161)), ContextData(),
        ObjectType(
            ObjectIdentity('1.3.6.1.4.1.318.1.1.26.9.4.3.1.7.' +
                           str(pdu_node_port))),
        ObjectType(ObjectIdentity('1.3.6.1.4.1.318.2.1.6.1.0')),
        ObjectType(ObjectIdentity('1.3.6.1.4.1.318.2.1.6.2.0')))

    watt = None
    timestamp = None

    if errorIndication:
        LOGGER.error(errorIndication)
    elif errorStatus:
        LOGGER.error('%s at %s' %
                     (errorStatus.prettyPrint(),
                      errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
    else:
        watt = int(varBinds[0][1])
        timestamp_str = str(varBinds[1][1]) + " " + str(varBinds[2][1])
        timestamp = int(
            time.mktime(
                datetime.datetime.strptime(timestamp_str,
                                           "%m/%d/%Y %H:%M:%S").timetuple()))

    snmpEngine.transportDispatcher.closeDispatcher()

    return watt, timestamp
Esempio n. 6
0
def snmp_polling(queue): #This is to query SNMP OID, and the data transferred to plot_drawing() using Queue() between multiproces.
    
        snmpEngine = SnmpEngine()
        loop = asyncio.get_event_loop()

        task = loop.create_task(async_next_snmp_request(snmpEngine, HOSTNAME, OIDS, SLEEP_TIME_1,comment_1 ,queue))  

        loop.run_until_complete(task)
    
        loop.run_until_complete(unconfigure(snmpEngine)) 
        loop.close()
Esempio n. 7
0
async def collect_periodically(work, result_queue, interval):
    snmp_engine = SnmpEngine()
    deadline = time.time() + interval
    while True:
        get_data = []
        while deadline <= time.time():
            logging.warning('missed deadline')
            deadline += interval
        sleep_var = deadline - time.time()
        await asyncio.sleep(sleep_var)
        deadline += interval
        for host, community_string, objects in work:
            get_data.append(
                get_one(snmp_engine, (host, 161), community_string, objects))

        ret = await asyncio.gather(*get_data)

        #print("Worker putting {} results into queue...".format(len(ret)))
        for r in ret:
            if r:
                result_queue.put_nowait(r)
Esempio n. 8
0
class SNMPEngine:
    requests = []
    targets = []
    results = []
    community_string = ''
    timeout = 0
    snmpEngine = 0
    loop = 0
    queue = 0
    mibViewController = 0

    def __init__(self, targets):
        self.requests = []
        self.targets = targets
        self.results = []
        self.community_string = get_config('snmp')['COMM_STRING']
        self.timeout = get_config('snmp')['TIMEOUT']
        self.snmpEngine = SnmpEngine()
        self.mibBuilder = self.snmpEngine.getMibBuilder()
        self.mibViewController = view.MibViewController(self.mibBuilder)
        self.loop = asyncio.get_event_loop()

    # process a single SNMP request asynchronously, requires host and snmp_object
    async def send_snmp_request(self, host, target):

        response = await getCmd(
            self.snmpEngine,
            CommunityData(self.community_string, mpModel=1),
            UdpTransportTarget((host, 161)),
            ContextData(),
            target,
        )

        error_indication, error_status, error_index, varbinds = response

        if error_indication:
            logger.warning('%s with this asset: %s', error_indication, host)
            return

        elif error_status:
            logger.warning(
                '%s at %s',
                error_status.prettyPrint(),
            )
            return

        else:
            return varbinds[0]

    # build loop tasks from attached target data
    # with metadata appended
    def enqueue_requests(self):
        logger.info('enqueueing requests..')

        for target in self.targets:
            for equipment in target.contains:
                for oid_obj in equipment.oid_obj_array:

                    # appending parent equipment data label to oid metadata array for later organization
                    metadata_dict = oid_obj.get_metadata_dict()
                    metadata_dict.update({'label': equipment.get_label()})

                    # appending targets to requests queue
                    self.requests.append({
                        self.loop.create_task(
                            self.send_snmp_request(equipment.ip, oid_obj.snmp_object)):
                        metadata_dict
                    })

    def process_requests(self):
        logger.info('processing request queue..')
        response_data = []
        failures = 0

        for request in self.requests:
            for snmp_request, metadata in request.items():
                response = self.loop.run_until_complete(snmp_request)

                if response:

                    payload = str(response).split('=', 1)[1].lstrip()

                    # did our formatted payload response create an integer? if so, success
                    try:
                        if payload:
                            payload = int(payload) / metadata['divisor']

                            metadata.update({'payload': payload})
                    except ValueError:
                        logger.warning(
                            'failed integer division for payload from {0}'.
                            format(metadata['label']))
                        failures += 1

                    response_data.append(metadata)

                else:
                    failures += 1

        if failures:
            logger.warning(
                '{0} snmp attempts not returned from snmp'.format(failures))

        self.requests.clear()
        return response_data

    def test(self, oid, ip):
        request = self.loop.create_task(
            self.send_snmp_request(ip, ObjectType(ObjectIdentity(oid))))

        response = self.loop.run_until_complete(request)

        return response