def _update_battery_oids(self, charge_level, old_level): """Update OIDs associated with UPS Battery Args: charge_level(int): new battery level (between 0 & 1000) """ # 100% oid_adv = self.get_oid_by_name("AdvBatteryCapacity") oid_hp = self.get_oid_by_name("HighPrecBatteryCapacity") oid_basic = self.get_oid_by_name("BasicBatteryStatus") if oid_adv: self._update_oid_value(oid_adv, snmp_data_types.Gauge32(charge_level / 10)) if oid_hp: self._update_oid_value(oid_hp, snmp_data_types.Gauge32(charge_level)) if not oid_basic: return if charge_level <= 100: low_bat_value = oid_basic.specs["batteryLow"] self._update_oid_value(oid_basic, snmp_data_types.Integer32(low_bat_value)) elif old_level <= 100 < charge_level: norm_bat_value = oid_basic.specs["batteryNormal"] self._update_oid_value(oid_basic, snmp_data_types.Integer32(norm_bat_value))
def _update_current_oids(self, load): """Update OIDs associated with UPS Output - Current in AMPs Args: load(float): new load in AMPs """ oid_adv = self.get_oid_by_name("AdvOutputCurrent") oid_hp = self.get_oid_by_name("HighPrecOutputCurrent") if oid_adv: self._update_oid_value(oid_adv, snmp_data_types.Gauge32(load)) if oid_hp: self._update_oid_value(oid_hp, snmp_data_types.Gauge32(load * 10))
def add_ipv6_address(self, address): """ Add the given IPv6 address to the VLAN. `address` should be of type ipaddress.IPv6Interface. """ # TODO: Convert a HP-ICF-IPCONFIG with this OID to pysnmp format hpicfIpv6InterfaceCfgEnableStatus = (1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 10, 3, 2, 1, 1, 6) hpicfIpv6InterfaceManual = (1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 10, 3, 2, 1, 1, 2) ipv6_address_tuple = struct.unpack("16B", address.ip.packed) self.switch.snmp_set( # Set enabled and configure a link-local address (hpicfIpv6InterfaceCfgEnableStatus + (self.ifindex, ), rfc1902.Integer(1)), # Enable manual address configuration (hpicfIpv6InterfaceManual + (self.ifindex, ), rfc1902.Integer(1)), (("ipv6InterfaceEnableStatus", self.ifindex), rfc1902.Integer(1)), (("hpicfIpAddressPrefixLength", self.ifindex, 2, 16) + ipv6_address_tuple, rfc1902.Gauge32(address.prefixlen)), # hpicfIpAddressType unicast (("hpicfIpAddressType", self.ifindex, 2, 16) + ipv6_address_tuple, rfc1902.Integer(1)), # hpicfIpAddressRowStatus createAndGo 4 (("hpicfIpAddressRowStatus", self.ifindex, 2, 16) + ipv6_address_tuple, rfc1902.Integer(4)))
def __coerce_value(initial_value, new_value): """Coerce the new_value to the same type as the initial_value. :param initial_value: initial value from the device :param new_value: new value to set, coerced into the right type :return: new value, coerced into the right type """ # pylint: disable=redefined-variable-type # In order to return the right type the return value has to be # redefined. # Types from RFC-1902 if isinstance(initial_value, rfc1902.Counter32): set_value = rfc1902.Counter32(str(new_value)) elif isinstance(initial_value, rfc1902.Counter64): set_value = rfc1902.Counter64(str(new_value)) elif isinstance(initial_value, rfc1902.Gauge32): set_value = rfc1902.Gauge32(str(new_value)) elif isinstance(initial_value, rfc1902.Integer): set_value = rfc1902.Integer(str(new_value)) elif isinstance(initial_value, rfc1902.Integer32): set_value = rfc1902.Integer32(str(new_value)) elif isinstance(initial_value, rfc1902.IpAddress): set_value = rfc1902.IpAddress(str(new_value)) elif isinstance(initial_value, rfc1902.OctetString): set_value = rfc1902.OctetString(str(new_value)) elif isinstance(initial_value, rfc1902.TimeTicks): set_value = rfc1902.TimeTicks(str(new_value)) elif isinstance(initial_value, rfc1902.Unsigned32): set_value = rfc1902.Unsigned32(str(new_value)) else: raise RuntimeError("Unknown type %s" % type(initial_value)) return set_value
def _switchport_mode_trunk_init(self, nos_host, port_num): """Enable a port as VLAN trunk mode.""" LOG.debug(_('_switchport_mode_trunk_init %s %d'), nos_host, port_num) oid_table = self._get_oid_table(nos_host) """Change switchport to trunk mode, and set PVID = 1""" varBinds = [] TAGGED = 2 snmp_oid = oid_enterprise + oid_table['agPortNewCfgVlanTag'] + (port_num,) value = rfc1902.Integer(TAGGED) varBinds += (snmp_oid, value), snmp_oid = oid_enterprise + oid_table['agPortNewCfgPVID'] + (port_num,) value = rfc1902.Integer32(1) varBinds += (snmp_oid, value), self._set(nos_host, varBinds) """Remove all other VLAN except 1 for the first time config this port""" max_vlan_id = 4094 vlans = range(2, max_vlan_id+1) varBinds = [] for vid in vlans: snmp_oid = oid_enterprise + oid_table['vlanNewCfgRemovePort'] + (vid,) value = rfc1902.Gauge32(port_num) varBinds += (snmp_oid, value), if vid%20 == 0: self._set(nos_host, varBinds) varBinds = [] self._set(nos_host, varBinds)
def _set_port_untagged_status(self, port, status): previous_untagged_vlan = port.untagged_vlan if status == True: # To add a port to a VLAN untagged, it first needs to be added as tagged self.add_tagged_port(port) # Add the port to the list of untagged ports for this VLAN dot1qVlanStaticUntaggedPorts = self.switch.snmp_get( ("dot1qVlanStaticUntaggedPorts", self.vid)) new_untagged_port_list = VLAN._set_port_list_port_status( dot1qVlanStaticUntaggedPorts, port, status) if dot1qVlanStaticUntaggedPorts != new_untagged_port_list: self.switch.snmp_set((("dot1qVlanStaticUntaggedPorts", self.vid), rfc1902.OctetString(new_untagged_port_list))) # Only set the pvid if the port is being added to the VLAN if status == True: dot1qPvid = self.switch.snmp_get(("dot1qPvid", port.base_port)) if dot1qPvid != self.vid: self.switch.snmp_set( (("dot1qPvid", port.base_port), rfc1902.Gauge32(self.vid))) # Remove the port from the VLAN that it belonged to before if previous_untagged_vlan is not None and self != previous_untagged_vlan: previous_untagged_vlan.remove_untagged_port(port) # If the port was just removed from dot1qVlanStaticUntaggedPorts, it is still in dot1qVlanStaticEgressPorts and # therefore still egresses this VLAN tagged if status == False: self.remove_tagged_port(port)
def _update_current(self, load): """Update OID associated with the current amp value""" oid = self.get_oid_by_name("AmpOnPhase") if not oid: return self._update_oid_value(oid, snmp_data_types.Gauge32(max(load, 0) * 10))
def _update_load_perc_oids(self, load): """Update OIDs associated with UPS Output - % of the power capacity Args: load(float): new load in AMPs """ oid_adv = self.get_oid_by_name("AdvOutputLoad") oid_hp = self.get_oid_by_name("HighPrecOutputLoad") value_hp = abs( (1000 * (load * state_api.ISystemEnvironment.get_voltage())) / self.output_capacity) if oid_adv: self._update_oid_value(oid_adv, snmp_data_types.Gauge32(value_hp / 10)) if oid_hp: self._update_oid_value(oid_hp, snmp_data_types.Gauge32(value_hp))
def snmpset(self,*args): '''This api is used for oid snmpset operation''' self.snmp_target = (self.host,self.snmp_port) cg = cmdgen.CommandGenerator() comm_data = cmdgen.CommunityData('my-manager', self.community_string) transport = cmdgen.UdpTransportTarget(self.snmp_target) snmpset_data = [] for i in range(len(args[0])): print("\nSNMP COMMAND : " + "snmpset -v2c -c " + self.community_string + ' ' + self.snmp_target[0] + ' ' + args[0][i][0] +' '+ args[0][i][2] +' '+args[0][i][1]+"\n") snmpset_data.append("\nSNMP COMMAND : " + "snmpset -v2c -c " + self.community_string + ' ' + self.snmp_target[0] + ' ' + args[0][i][0] +' '+ args[0][i][2] +' '+args[0][i][1]+"\n") print("<<<<<<<<OUTPUT>>>>>>>>>") snmpset_data.append("<<<<<<<<OUTPUT>>>>>>>>>") if args[0][i][2] == "s": variables = (args[0][i][0], rfc1902.OctetString(args[0][i][1])) errIndication, errStatus, errIndex, result = cg.setCmd(comm_data, transport,variables) snmpset_data.append(result) elif args[0][i][2] == "i": variables = (args[0][i][0], rfc1902.Integer(args[0][i][1])) errIndication, errStatus, errIndex, result = cg.setCmd(comm_data, transport,variables) snmpset_data.append(result) elif args[0][i][2] == "o": variables = (args[0][i][0], rfc1902.Bits(args[0][i][1])) errIndication, errStatus, errIndex, result = cg.setCmd(comm_data, transport,variables) snmpset_data.append(result) elif args[0][i][2] == "t": variables = (args[0][i][0], rfc1902.TimeTicks(args[0][i][1])) errIndication, errStatus, errIndex, result = cg.setCmd(comm_data, transport,variables) snmpset_data.append(result) elif args[0][i][2] == "u": variables = (args[0][i][0], rfc1902.Unsigned32(args[0][i][1])) errIndication, errStatus, errIndex, result = cg.setCmd(comm_data, transport,variables) snmpset_data.append(result) elif args[0][i][2] == "ip": variables = (args[0][i][0], rfc1902.IpAddress(args[0][i][1])) errIndication, errStatus, errIndex, result = cg.setCmd(comm_data, transport,variables) snmpset_data.append(result) elif args[0][i][2] == "U": variables = (args[0][i][0], rfc1902.Gauge32(args[0][i][1])) errIndication, errStatus, errIndex, result = cg.setCmd(comm_data, transport,variables) snmpset_data.append(result) else: pass # Check for errors and print out results if errIndication: print(errIndication) snmpset_data.append(errIndication) elif errStatus: print("REASON :" + '%s at %s' % (errStatus.prettyPrint(),errIndex and result[int(errIndex) - 1][0] or '?')) snmpset_data.append("REASON : "+ '%s at %s' % (errStatus.prettyPrint(),errIndex and result[int(errIndex) - 1][0] or '?')) else: for name, val in result: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) snmpset_data.append(name.prettyPrint() +" = "+ val.prettyPrint()) return snmpset_data
def process_voltage(self, voltage): """Update oids associated with UPS voltage Args: voltage: new voltage value Returns: tuple: true if transfer to battery is needed, transfer reason (see state.api.ups.UPS.InputLineFailCause) Raises: ValueError: if UPS has no voltage OIDs defined or transfer reason cannot be determined """ oid_in_adv = self.get_oid_by_name("AdvInputLineVoltage") oid_out_adv = self.get_oid_by_name("AdvOutputVoltage") if not oid_in_adv or not oid_out_adv: raise ValueError("UPS doesn't support voltage OIDs!") oid_voltage_value = snmp_data_types.Gauge32(int(voltage)) # update input OID parameter self._update_oid_value(oid_in_adv, oid_voltage_value) # retrieve thresholds: oid_high_th = self.get_oid_by_name("AdvConfigHighTransferVolt") oid_low_th = self.get_oid_by_name("AdvConfigLowTransferVolt") # update output OID value if thresholds are not supported if not oid_high_th or not oid_low_th: self._update_oid_value(oid_out_adv, oid_voltage_value) return False, None high_th = int(self.get_oid_value(oid_high_th)) low_th = int(self.get_oid_value(oid_low_th)) # new voltage value is within the threasholds if low_th < voltage < high_th: self._update_oid_value(oid_out_adv, oid_voltage_value) return False, None # new voltage should cause line transfer: r_out_threshold = self.rated_output_threshold if 0 <= voltage < r_out_threshold: transfer_reason = self.InputLineFailCause.deepMomentarySag elif r_out_threshold <= voltage <= low_th: transfer_reason = self.InputLineFailCause.smallMomentarySag elif voltage >= high_th: transfer_reason = self.InputLineFailCause.highLineVoltage else: raise ValueError("Unknow transfer reason!") return True, transfer_reason
def _enable_vlan_on_port(self, nos_host, vlan_id, port_num): """Enable a VLAN on a port interface.""" LOG.debug(_('_enable_vlan_on_port %s %d %d'), nos_host, vlan_id, port_num) oid_table = self._get_oid_table(nos_host) varBinds = [] snmp_oid = oid_enterprise + oid_table['vlanNewCfgAddPort'] + (vlan_id,) value = rfc1902.Gauge32(port_num) varBinds += (snmp_oid, value), self._set(nos_host, varBinds)
def makeSnmpObj_rfc1902(*args): oid_type = [] for oid, type, value in args: #print(oid, type, value) if type == 'Integer': obj = rfc1902.Integer(value) else: if type == 'Gauge': obj = rfc1902.Gauge32(value) else: raise SnmpSetError oid_type.append((oid, obj)) return (oid_type)
def add_ipv4_address(self, address): """ Add the given IPv4 address to the VLAN. `address` should be of type ipaddress.IPv4Interface. """ ipv4_address_tuple = struct.unpack("4B", address.ip.packed) self.switch.snmp_set( (("ipv4InterfaceEnableStatus", self.ifindex), rfc1902.Integer(1)), # hpicfIpv4InterfaceDhcpEnable off (("hpicfIpv4InterfaceDhcpEnable", self.ifindex), rfc1902.Integer(2) ), (("hpicfIpAddressPrefixLength", self.ifindex, 1, 4) + ipv4_address_tuple, rfc1902.Gauge32(address.prefixlen)), # hpicfIpAddressType unicast (("hpicfIpAddressType", self.ifindex, 1, 4) + ipv4_address_tuple, rfc1902.Integer(1)), # hpicfIpAddressRowStatus createAndGo 4 (("hpicfIpAddressRowStatus", self.ifindex, 1, 4) + ipv4_address_tuple, rfc1902.Integer(4)))
def _switchport_mode_trunk_init(self, nos_host, port_num): """Enable a port as VLAN trunk mode.""" LOG.debug(_('_switchport_mode_trunk_init %s %d'), nos_host, port_num) oid_table = self._get_oid_table(nos_host) """Change switchport to trunk mode, and set PVID = 1""" varBinds = [] TAGGED = 2 snmp_oid = oid_enterprise + oid_table['agPortNewCfgVlanTag'] + (port_num,) value = rfc1902.Integer(TAGGED) varBinds += (snmp_oid, value), snmp_oid = oid_enterprise + oid_table['agPortNewCfgPVID'] + (port_num,) value = rfc1902.Integer32(1) varBinds += (snmp_oid, value), self._set(nos_host, varBinds) """Remove all other VLAN except 1 for the first time config this port""" try: switchHW = oid_table["device"] except KeyError: switchHW = "" if switchHW == "Piglet":#vlan range always 1-4094 for piglet, different from other switches max_vlan_id = 4094 else: max_vlan_id = 4094 if self._support_old_release(nos_host) else 4095 vlans = range(2, max_vlan_id+1) varBinds = [] for vid in vlans: snmp_oid = oid_enterprise + oid_table['vlanNewCfgRemovePort'] + (vid,) value = rfc1902.Gauge32(port_num) varBinds += (snmp_oid, value), if vid%20 == 0: self._set(nos_host, varBinds) varBinds = [] self._set(nos_host, varBinds)
def _to_pysnmp(self, value): """ Convert connection plugin object into pysnmp objects """ if value is None: return None if isinstance(value, OctetString): return rfc1902.OctetString(str(value.value)) if isinstance(value, ObjectIdentifier): return rfc1902.ObjectName(str(value.value)) if isinstance(value, Integer32): return rfc1902.Integer32(int(value.value)) if isinstance(value, Counter32): return rfc1902.Counter32(long(value.value)) if isinstance(value, IpAddress): return rfc1902.IpAddress(str(value.value)) if isinstance(value, Gauge32): return rfc1902.Gauge32(long(value.value)) if isinstance(value, TimeTicks): return rfc1902.TimeTicks(long(value.value)) if isinstance(value, Opaque): return rfc1902.Opaque(value.value) # FIXME if isinstance(value, Counter64): return rfc1902.Counter64(str(value.value)) raise SnmpError('Invalid type: %s' % value.__class__.__name__)
def update_temperature(self, temp): """Set battery temperature of the device""" oid_value = (temp + state_api.ISystemEnvironment.get_ambient()) * 10 self._update_oid_by_name("HighPrecBatteryTemperature", snmp_data_types.Gauge32(oid_value))
# GMT: Friday, 7 May 2021 11:23:00 expect(snmp_value.to_timestamp()).to(equal(1620386580.0)) with context('when type is IpAddress'): with it('checks value and type'): snmp_data = rfc1902.IpAddress('127.0.0.1') snmp_value = PySnmpValue(snmp_data) expect(snmp_value.value()).to(equal('127.0.0.1')) expect(snmp_value.type_text()).to(equal('IpAddress')) with context('when type is Gauge32'): with it('checks value and type'): snmp_data = rfc1902.Gauge32(42) snmp_value = PySnmpValue(snmp_data) expect(snmp_value.value()).to(equal(42)) expect(snmp_value.type_text()).to(equal('Gauge32')) with context('when type is ObjectIdentifier'): with it('checks value and type'): snmp_data = univ.ObjectIdentifier('1.1') snmp_value = PySnmpValue(snmp_data) expect(snmp_value.value()).to(equal('1.1')) expect(snmp_value.type_text()).to(equal('ObjectIdentifier'))
def convert_to_gauge32(self, value): """Converts a value to a SNMP Gauge32 object.""" return rfc1902.Gauge32(value)