class CyberPowerPdu(PowerDevice): """Power unit from CyberPower.""" def __init__(self, ip_address, outlet, username="******", password="******"): """Instance initialization.""" PowerDevice.__init__(self, ip_address, username, password) self.port = outlet self.ip_address = ip_address self.oid_Outlet = "1.3.6.1.4.1.3808.1.1.3.3.3.1.1.4" self.session = Session(hostname=self.ip_address, community="private", version=2) def on(self): """Send ON command.""" oid = self.oid_Outlet + "." + str(self.port) self.session.set(oid, 1, "i") def off(self): """Send OFF command.""" oid = self.oid_Outlet + "." + str(self.port) self.session.set(oid, 2, "i") def reset(self): """Send OFF command, wait 5 seconds, sned ON command.""" self.off() time.sleep(5) self.on()
class CyberPowerPdu(PowerDevice): '''Power unit from CyberPower.''' def __init__(self, ip_address, outlet, username='******', password='******'): PowerDevice.__init__(self, ip_address, username, password) self.port = outlet self.ip_address = ip_address self.oid_Outlet = '1.3.6.1.4.1.3808.1.1.3.3.3.1.1.4' self.session = Session(hostname=self.ip_address, community="private", version=2) def on(self): '''Send ON command.''' oid = self.oid_Outlet + '.' + str(self.port) self.session.set(oid, 1, 'i') def off(self): '''Send OFF command.''' oid = self.oid_Outlet + '.' + str(self.port) self.session.set(oid, 2, 'i') def reset(self): '''Send OFF command, wait 5 seconds, sned ON command.''' self.off() time.sleep(5) self.on()
def rel_set(CONFIG, value): # Create an SNMP session to be used for all our requests session = Session(hostname=CONFIG['SDS_IP'], community=CONFIG['SDS_COMUNITY'], version=1) # And of course, you may use the numeric OID too session.set('.1.3.6.1.4.1.33283.1.2.3.4.0', value, 'integer')
class SNMP_Service(): def __init__(self, hostname, **kwargs): self.switch = hostname self.version = kwargs.get('version', 2) if self.version < 3: self.community = kwargs.get('community', 'public') self.session = Session(hostname=self.switch, community=self.community, version=self.version) else: self.security_level = kwargs.get('security_level', 'authNoPriv') self.security_username = kwargs.get('security_username', 'opro') self.auth_protocol = kwargs.get('auth_protocol', 'SHA') self.auth_password = kwargs.get('auth_password', '') self.privacy_protocol = kwargs.get('privacy_protocol', 'aes') self.privacy_password = kwargs.get('privacy_password', '') self.session = Session(hostname=self.switch, security_level=self.security_level, security_username=self.security_username, auth_protocol=self.auth_protocol, auth_password=self.auth_password, privacy_protocol=self.privacy_protocol, privacy_password=self.privacy_password, version=self.version) def sys_descr(self): d = self.session.get('sysDescr.0') [descr, fw, rom] = d.value.split(',') return (self.switch, descr, fw, rom) def num_ports(self): d = self.session.get('') [descr, fw, rom] = d.value.split(',') def model(self): d = self.session.get('ENTITY-MIB::entPhysicalModelName.1') return d def firmware(self): d = self.session.get('ENTITY-MIB::entPhysicalSoftwareRev.1') return d def get(self, oid): return self.session.get(oid) def getfirst(self, oid): ret = self.session.get_next(oid) while ret is not None and not len(ret.value): ret = self.session.get_next(ret.oid) return ret def getall(self, oid, filter_by_value=False): ret = self.session.walk(oid) if filter_by_value: return [lambda x: x.value for x in ret] return ret def set(self, oid, value, snmp_type=None): return self.session.set(oid, value, snmp_type) def set_multiple(self, oids): return self.session.set_multiple(oids)
class CyberPowerPdu(PDUTemplate): """Power unit from CyberPower.""" def __init__( self, ip_address: str, port: Any, username: str = "cyber", password: str = "cyber", outlet="", ): """Instance initialization.""" super().__init__( ip_address, username, password, conn_port=port, outlet="1.3.6.1.4.1.3808.1.1.3.3.3.1.1.4", ) self.session = Session(hostname=self.ip_address, community="private", version=2) def _connect(self): raise NotImplementedError def __on(self): """Send ON command.""" oid = self.outlet + "." + str(self.conn_port) self.session.set(oid, 1, "i") def __off(self): """Send OFF command.""" oid = self.oid_Outlet + "." + str(self.conn_port) self.session.set(oid, 2, "i") def reset(self): """Send OFF command, wait 5 seconds, send ON command.""" self.__off() time.sleep(5) self.__on() def turn_off(self): """Send OFF command""" self.__off()
def set(self, oid: str, value, data_type='i'): """ :param oid: 'PDU2-MIB::externalSensorType.1.1' :param value: 8 :param data_type: :return: """ s = Session(hostname=self.host, community=self.community_write, version=self.version) r = s.set(oid, value, data_type) return r
class SnmpOperations: def __init__(self, host_name): self.hostname = host_name self.session = Session(hostname=self.hostname, community='public', version=3, timeout=10, retries=1, security_level='auth_with_privacy', security_username='******', privacy_protocol='DES', privacy_password='******', auth_protocol='MD5', auth_password='******') def config_upgrade_activate(self, device_type, action_type, filename, filesize, filemd5, ftpAddr, ftpType, ftpUser, ftpPass, ftpPort, mac): task_id = (strftime("%M%Y%H%S", time.gmtime())) if device_type == 'proxy' and action_type == 'config': mystring = ftpType + ' ' + ftpAddr + ' ' + ftpPort + ' ' + ftpUser + ' ' + ftpPass + ' ' + 'null {\"CMD\":[{\"TSK\":{\"ID\":' + task_id +',\"TGT\":[],\"ACT\":{\"NAME\":\"CONFIG\",\"PRIO\":100,\"EXP\":\"2100-12-24T18:53:44+00:00\",\"SET\":{\"ID\":\"' + filename + '\",\"SZ\":' + filesize +',\"SIG\":\"' + filemd5+ '\",\"DST\":0,\"EDT\":\"2016-06-24T16:53:44+00:00\",\"CM\":0}}}}]}' if self.session.set('1.3.6.1.4.1.6232.8.1.3.1.0', str(mystring), 's'): return mystring else: return "SNMPSET FAILURE!" #return str(self.session.set('1.3.6.1.4.1.6232.8.1.3.1.0', str(mystring), 's')) elif device_type == 'bpl' and action_type == 'config': mystring = ftpType + ' ' + ftpAddr + ' ' + ftpPort + ' ' + ftpUser + ' ' + ftpPass + ' ' + 'null {\"CMD\":[{\"TSK\":{\"ID\":' + task_id +',\"TGT\":[{\"DEV_ID\":\"' + mac + '\"}],\"ACT\":{\"NAME\":\"CONFIG\",\"PRIO\":100,\"EXP\":\"2100-12-24T18:53:44+00:00\",\"SET\":{\"ID\":\"' + filename + '\",\"SZ\":' + filesize +',\"SIG\":\"' + filemd5+ '\",\"DST\":1,\"EDT\":\"2016-06-24T16:53:44+00:00\",\"CM\":0}}}}]}' if self.session.set('1.3.6.1.4.1.6232.8.1.3.1.0', str(mystring), 's'): return mystring else: return "SNMPSET FAILURE!" #return self.session.set('1.3.6.1.4.1.6232.8.1.3.1.0', str(mystring), 's') elif device_type == 'proxy' and action_type == 'upgrade': mystring = ftpType + ' ' + ftpAddr + ' ' + ftpPort + ' ' + ftpUser + ' ' + ftpPass + ' ' + 'null {\"CMD\":[{\"TSK\":{\"ID\":' + task_id +',\"TGT\":[],\"ACT\":{\"NAME\":\"UPGRADE\",\"PRIO\":100,\"EXP\":\"2100-12-24T18:53:44+00:00\",\"SET\":{\"ID\":\"' + filename + '\",\"SZ\":' + filesize +',\"SIG\":\"' + filemd5+ '\",\"DST\":0,\"EDT\":\"2016-06-24T16:53:44+00:00\",\"CM\":0}}}}]}' if self.session.set('1.3.6.1.4.1.6232.8.1.3.1.0', str(mystring), 's'): return mystring else: return "SNMPSET FAILURE!" #return self.session.set('1.3.6.1.4.1.6232.8.1.3.1.0', str(mystring), 's') elif device_type == 'bpl' and action_type == 'upgrade': mystring = ftpType + ' ' + ftpAddr + ' ' + ftpPort + ' ' + ftpUser + ' ' + ftpPass + ' ' + 'null {\"CMD\":[{\"TSK\":{\"ID\":' + task_id +',\"TGT\":[{\"DEV_ID\":\"' + mac + '\"}],\"ACT\":{\"NAME\":\"UPGRADE\",\"PRIO\":100,\"EXP\":\"2100-12-24T18:53:44+00:00\",\"SET\":{\"ID\":\"' + filename + '\",\"SZ\":' + filesize +',\"SIG\":\"' + filemd5+ '\",\"DST\":1,\"EDT\":\"2016-06-24T16:53:44+00:00\",\"CM\":0}}}}]}' if self.session.set('1.3.6.1.4.1.6232.8.1.3.1.0', str(mystring), 's'): return mystring else: return "SNMPSET FAILURE!" #return self.session.set('1.3.6.1.4.1.6232.8.1.3.1.0', str(mystring), 's') elif device_type == 'proxy' and action_type == 'activate': mystring = ftpType + ' ' + ftpAddr + ' ' + ftpPort + ' ' + ftpUser + ' ' + ftpPass + ' ' + 'null {\"CMD\":[{\"TSK\":{\"ID\":' + task_id + ',\"TGT\":[],\"ACT\":{\"NAME\":\"ACTIVATE\",\"PRIO\":100,\"EXP\":\"2100-12-24T18:53:44+00:00\",\"SET\":{\"ID\":\"' + filename + '\",\"SZ\":' + filesize + ',\"SIG\":\"' + filemd5 + '\",\"DST\":0,\"EDT\":\"2016-06-24T16:53:44+00:00\",\"CM\":0}}}}]}' if self.session.set('1.3.6.1.4.1.6232.8.1.3.1.0', str(mystring), 's'): return mystring else: return "SNMPSET FAILURE!" #return self.session.set('1.3.6.1.4.1.6232.8.1.3.1.0', str(mystring), 's') elif device_type == 'bpl' and action_type == 'activate': mystring = ftpType + ' ' + ftpAddr + ' ' + ftpPort + ' ' + ftpUser + ' ' + ftpPass + ' ' + 'null {\"CMD\":[{\"TSK\":{\"ID\":' + task_id + ',\"TGT\":[{\"DEV_ID\":\"' + mac + '\"}],\"ACT\":{\"NAME\":\"ACTIVATE\",\"PRIO\":100,\"EXP\":\"2100-12-24T18:53:44+00:00\",\"SET\":{\"ID\":\"' + filename + '\",\"SZ\":' + filesize + ',\"SIG\":\"' + filemd5 + '\",\"DST\":1,\"EDT\":\"2016-06-24T16:53:44+00:00\",\"CM\":0}}}}]}' if self.session.set('1.3.6.1.4.1.6232.8.1.3.1.0', str(mystring), 's'): return mystring else: return "SNMPSET FAILURE!" #return self.session.set('1.3.6.1.4.1.6232.8.1.3.1.0', str(mystring), 's') else: return 'Please select choose valid option (config/upgrade/activate)' def snmpget(self, oid):
class SNMPBaseWorker(object, metaclass=ABCMeta): ses = None def __init__(self, ip: Optional[str], community='public', ver=2): if ip is None or ip == '': raise DeviceImplementationError(gettext('Ip address is required')) self._ip = ip self._community = community self._ver = ver def start_ses(self): if self.ses is None: self.ses = Session( hostname=self._ip, community=self._community, version=self._ver ) def set_int_value(self, oid: str, value): self.start_ses() return self.ses.set(oid, value, 'i') def get_list(self, oid) -> Generator: self.start_ses() for v in self.ses.walk(oid): yield v.value def get_list_keyval(self, oid) -> Generator: self.start_ses() for v in self.ses.walk(oid): snmpnum = v.oid.split('.')[-1:] yield v.value, snmpnum[0] if len(snmpnum) > 0 else None def get_item(self, oid): self.start_ses() v = self.ses.get(oid).value if v != 'NOSUCHINSTANCE': return v
from easysnmp import Session # Create an SNMP session to be used for all our requests session = Session(hostname='192.168.40.1', community='cisco', version=2) # You may retrieve an individual OID using an SNMP GET location = session.get('sysLocation.0') # You may also specify the OID as a tuple (name, index) # Note: the index is specified as a string as it can be of other types than # just a regular integer contact = session.get(('sysContact', '0')) # And of course, you may use the numeric OID too description = session.get('.1.3.6.1.2.1.1.1.0') # Set a variable using an SNMP SET session.set('sysLocation.0', 'The SNMP Lab') # Perform an SNMP walk system_items = session.walk('system') # Each returned item can be used normally as its related type (str or int) # but also has several extended attributes with SNMP-specific information for item in system_items: print '{oid}.{oid_index} {snmp_type} = {value}'.format( oid=item.oid, oid_index=item.oid_index, snmp_type=item.snmp_type, value=item.value)
def snmp_test(): ip = input('\nEnter the device IP address: ') community = input('\nEnter the SNMP community: ') #oid = input('\nEnter the OID or MIB name to work on: ') #Opening the SNMP session to the device session = Session(hostname = ip, community = community, version = 2) while True: #User input print ('\nChoose the SNMP operation you want to perform:\n\n1 - SNMP GET\n2 - SNMP SET\n3 - SNMP WALK\ne - Exit program') user_choice = input('\nEnter your choice: ') if user_choice == '1': oid = input('\nEnter the OID or MIB name to work on: ') #Performing SNMP GET snmp_get = session.get(oid) #Getting the value returned by the device and coverting it to ASCII result = snmp_get.value #Printing the value print('\nThe result of SNMP GET on %s is:' % oid ) print ('\n' + result + '\n') continue elif user_choice == '2': oid = input('\nEnter the OID or MIB name to work on: ') #Asking the user what value should be set for oid value = input('\nEnter the value for the object: ') #Performing SNMP SET snmp_set = session.set(oid, value) print ('\nDone. Please check device %s.\n' % ip) continue elif user_choice == '3': oid = input('\nEnter the OID or MIB name to work on: ') #Performing SNMP WALK snmp_walk = session.walk(oid) #Printing the result print ('\nThe result of SNMP WALK on %s is:' % oid) for obj in snmp_walk: print ('\n' + obj.value) continue elif user_choice == 'e': print ('\nExiting program...\n' ) break else: print ('\nInvalid input. Exiting...\n') break #End Of Program
#Getting the value returned by the device and coverting it to ASCII result = snmp_get.value.encode('ascii') #Printing the value print '\nThe result of SNMP GET on %s is:' % oid print '\n' + result + '\n' continue elif user_choice == '2': #Asking the user what value should be set for oid value = raw_input('\nEnter the value for the object: ') #Performing SNMP SET snmp_set = session.set(oid, value) print '\nDone. Please check device %s.\n' % ip continue elif user_choice == '3': #Performing SNMP WALK snmp_walk = session.walk(oid) #Printing the result print '\nThe result of SNMP WALK on %s is:' % oid for obj in snmp_walk: print '\n' + obj.value.encode('ascii')
class Device(): def __init__(self, IPaddress, Port, Community, Version, Timeout): self.dev = Session(hostname=IPaddress, remote_port=Port, community=Community, version=Version, timeout=Timeout) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ READ METHODS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# #Method to numeric variable from regular OID def read_num(self, VarNameList, OIDList, MultiplierList): # Arguments: # VarNameList : list of variable name # OIDList : list of variable OID address # MultiplierList : list of multiplier # Return : dictionary of variable name and its value self.values = [] self.operation = math.ceil(len(OIDList) / dataPerAccess) i = 0 for opr in range(self.operation): try: data = self.dev.get(OIDList[i:i + dataPerAccess]) except: data = self.dev.get(OIDList[i:]) for item in data: self.values.append(int(item.value)) i += dataPerAccess for i in range(0, len(self.values)): self.values[i] = round(self.values[i] * MultiplierList[i], 3) self.Result = dict(zip(VarNameList, self.values)) return self.Result #Method to string variable from regular OID def read_string(self, VarNameList, OIDList): # Arguments: # VarNameList : list of variable name # OIDList : list of variable OID address # Return : dictionary of variable name and its value self.values = [] self.operation = math.ceil(len(OIDList) / dataPerAccess) i = 0 for opr in range(self.operation): try: data = self.dev.get(OIDList[i:i + dataPerAccess]) except: data = self.dev.get(OIDList[i:]) for item in data: self.values.append(str(item.value)) i += dataPerAccess self.Result = dict(zip(VarNameList, self.values)) return self.Result #Method to string variable from Table OID def read_num_tab(self, VarNameList, OIDList, rowList, MultiplierList): # Arguments: # VarNameList : list of variable name # OIDList : list of variable OID address # rowList : list of total row that we want to get from table column (max repetition in getBulk operation) # MultiplierList : list of multiplier # Return : dictionary of variable name and its value self.values = [] self.Result = {} i = 0 for oid in OIDList: data = self.dev.get_bulk(oid, max_repetitions=rowList[i]) j = 1 for item in data: self.Result[VarNameList[i] + "_%d" % j] = round( int(item.value) * MultiplierList[i], 3) j += 1 i += 1 return self.Result #Method to string variable from Table OID def read_string_tab(self, VarNameList, OIDList, rowList): # Arguments: # VarNameList : list of variable name # OIDList : list of variable OID address # rowList : list of total row that we want to get from table column (max repetition in getBulk operation) # Return : dictionary of variable name and its value self.values = [] self.Result = {} i = 0 for oid in OIDList: data = self.dev.get_bulk(oid, max_repetitions=rowList[i]) j = 1 for item in data: self.Result[VarNameList[i] + "_%d" % j] = str(item.value) j += 1 i += 1 return self.Result #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ WRITE METHODS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# # Method to write a value in single OID def write(self, OID, value, snmp_type=None): # Arguments: # OID : object identifier of a variable # value : value that you want to write in the OID # snmp_type : data type in object # if snmp_type == None: self.dev.set(registerAddress, value) else: self.dev.set(registerAddress, value, snmp_type) # Method to write values in multiple OIDs def write_multiple(self, OIDList, valueList, snmp_type=None): # Arguments: # OIDList : list of object identifier # valueList : list of value if snmp_type == None: oid_val = list(zip(OIDList, valueList)) self.dev.set_multiple(oid_val) else: oid_val = list(zip(OIDList, valueList, snmp_type)) self.dev.set_multiple(oid_val)
class PDUSNMP: def __init__(self, hostname, socket, login): self.flag = 0 if int(socket) < 9: self.socket = int(socket) + 1 else: self.socket = int(socket) + 2 self.mid_sk = f'.1.3.6.1.4.1.21317.1.3.2.2.2.2.{self.socket}.0' self.session = Session(hostname=hostname, community=login, version=2) def on(self): try: if self.session.get(self.mid_sk).value == '2': print('The socket is already on') return True elif self.session.get(self.mid_sk).value == '3': sleep(5) if self.flag > 3: print('Время ожидания превышено') self.flag = 0 return False self.flag += 1 self.on() self.flag = 0 return self.session.set(self.mid_sk, '2', 'INTEGER') except: print( 'Ошибка соединения, проверьте корректность данных и доступность стенда по порту 161' ) return False def off(self): try: if self.session.get(self.mid_sk).value == '1': print('The socket is already off') return True elif self.session.get(self.mid_sk).value == '3': sleep(5) if self.flag > 3: print('Время ожидания превышено') self.flag = 0 return False self.flag += 1 self.off() self.flag = 0 return self.session.set(self.mid_sk, '1', 'INTEGER') except: print( 'Ошибка соединения, проверьте корректность данных и доступность стенда по порту 161' ) return False def reboot(self): try: if self.session.get(self.mid_sk).value == '3': sleep(5) if self.flag > 3: print('Время ожидания превышено') self.flag = 0 return False self.flag += 1 self.reboot() self.flag = 0 return self.session.set(self.mid_sk, '4', 'INTEGER') except: print( 'Ошибка соединения, проверьте корректность данных и доступность стенда по порту 161' ) return False def status(self): dict_status = {'1': 'off', '2': 'on', '3': 'pending', '4': 'reboot'} if self.session.get(self.mid_sk).value == '3': sleep(5) print(dict_status.get(self.session.get(self.mid_sk).value)) return dict_status.get(self.session.get(self.mid_sk).value)