Perform an SNMP walk on a given OID
352015
def walk(self, oid, host, port, community):
        
        # Initialize return value
        ret = {}

        # Convert OID to tuple if necessary
        if not isinstance(oid, tuple):
            oid = self._convert_to_oid(oid)

        # Convert Host to IP if necessary
        host = socket.gethostbyname(host)

        # Assemble SNMP Auth Data
        snmpAuthData = cmdgen.CommunityData(
            'agent-{}'.format(community),
            community)

        # Assemble SNMP Transport Data
        snmpTransportData = cmdgen.UdpTransportTarget(
            (host, port),
            int(self.config['timeout']),
            int(self.config['retries']))

        # Assemble SNMP Next Command
        resultTable = self.snmpCmdGen.nextCmd(snmpAuthData,
                                              snmpTransportData,
                                              oid)
        varBindTable = resultTable[3]

        # TODO: Error Check

        for varBindTableRow in varBindTable:
            for o, v in varBindTableRow:
                ret[str(o)] = v.prettyPrint()

        return ret
1365542
def updatephysicalport(update_processor = partial(default_processor, excluding=('vhost', 'systemid',
                                                                                   'bridge', 'name'),
                                                                     disabled=('physicalnetwork',)),
                       reorder_dict = default_iterate_dict
                      ):
    
    def walker(walk, write, timestamp, parameters_dict):
        for key, parameters in reorder_dict(parameters_dict):
            try:
                value = walk(key)
            except KeyError:
                pass
            else:
                if update_processor(value, walk, write, parameters=parameters):
                    write(key, value)
    return walker
388231
def get_snmp_from_host2(self):
        
        if not self.snmp2:
            self.activity_value2 = None
        else:
            response = self.snmp2.get_oids(activity_oid)
            self.activity_value2 = activity[int(response[0])]
891374
def from_payload(self, payload):
        """"""
        self.session_id = payload[0]*256 + payload[1]
        self.index_id = payload[2]
        self.node_parameter = payload[3]
        self.seconds = payload[4]*256 + payload[5]
461969
def run(args):
    """"""

    repos = load_config(args.config, args.expand_env, args.force)

    jobs = max(args.jobs, 1)
    threads = []
    sem = threading.Semaphore(jobs)
    err_queue = Queue()

    for repo_dict in repos:
        if not err_queue.empty():
            break

        sem.acquire()
        r = Repo(**repo_dict)
        tname = os.path.basename(repo_dict['cwd'])

        if jobs > 1:
            t = threading.Thread(
                target=aggregate_repo, args=(r, args, sem, err_queue))
            t.daemon = True
            t.name = tname
            threads.append(t)
            t.start()
        else:
            with ThreadNameKeeper():
                threading.current_thread().name = tname
                aggregate_repo(r, args, sem, err_queue)

    for t in threads:
        t.join()

    if not err_queue.empty():
        while True:
            try:
                exc_type, exc_obj, exc_trace = err_queue.get_nowait()
            except EmptyQueue:
                break
            traceback.print_exception(exc_type, exc_obj, exc_trace)
        sys.exit(1)
944295
def collect(self, device, ip, user, password):
        

        if netappsdk is None:
            self.log.error(
                'Failed to import netappsdk.NaServer or netappsdk.NaElement')
            return

        if device in self.running:
            return

        self.running.add(device)
        prefix = self.config['path_prefix']
        pm = self.publish_metric

        netapp_inodeCol(device, ip, user, password, prefix, pm)
        self.running.remove(device)
329954
@Override
	public void index(String oid, String pid) throws IndexerException {
		try {
			DigitalObject object = storage.getObject(oid);
			Payload payload = object.getPayload(pid);
			index(object, payload);
		} catch (StorageException ex) {
			throw new IndexerException(ex);
		}
	}
554107
def objwalk(self, obj, path=(), memo=None):
        

        # dual python 2/3 compatability, inspired by the "six" library
        string_types = (str, unicode) if str is bytes else (str, bytes)
        iteritems = lambda mapping: getattr(mapping, 'iteritems', mapping.items)()

        if memo is None:
            memo = set()
        iterator = None
        if isinstance(obj, Mapping):
            iterator = iteritems
        elif isinstance(obj, (Sequence, Set)) and not isinstance(obj, string_types):
            iterator = enumerate
        if iterator:
            if id(obj) not in memo:
                memo.add(id(obj))
                for path_component, value in iterator(obj):
                    for result in self.objwalk(value, path + (path_component,), memo):
                        yield result
                memo.remove(id(obj))
        else:
            yield path, obj
335787
def __load_uri(self, sock_dir, node):
        '''
        
        '''
        if node == 'master':
            if self.opts['ipc_mode'] == 'tcp':
                puburi = int(self.opts['tcp_master_pub_port'])
                pulluri = int(self.opts['tcp_master_pull_port'])
            else:
                puburi = os.path.join(
                    sock_dir,
                    'master_event_pub.ipc'
                )
                pulluri = os.path.join(
                    sock_dir,
                    'master_event_pull.ipc'
                )
        else:
            if self.opts['ipc_mode'] == 'tcp':
                puburi = int(self.opts['tcp_pub_port'])
                pulluri = int(self.opts['tcp_pull_port'])
            else:
                hash_type = getattr(hashlib, self.opts['hash_type'])
                # Only use the first 10 chars to keep longer hashes from exceeding the
                # max socket path length.
                id_hash = hash_type(salt.utils.stringutils.to_bytes(self.opts['id'])).hexdigest()[:10]
                puburi = os.path.join(
                    sock_dir,
                    'minion_event_{0}_pub.ipc'.format(id_hash)
                )
                pulluri = os.path.join(
                    sock_dir,
                    'minion_event_{0}_pull.ipc'.format(id_hash)
                )
        log.debug('%s PUB socket URI: %s', self.__class__.__name__, puburi)
        log.debug('%s PULL socket URI: %s', self.__class__.__name__, pulluri)
        return puburi, pulluri
385459
def process_metrics(self, snmp_data):
        ""
        self.metrics = {}
        for i in range(0, len(snmp_data)):
            metric_id = self.models[self.modem_type]['metrics'][i]
            value = int(snmp_data[i])
            self.metrics[metric_id] = value
972494
def _do(name, fun, path=None):
    '''
    
    '''
    host = find_guest(name, quiet=True, path=path)
    if not host:
        return False

    client = salt.client.get_local_client(__opts__['conf_file'])
    cmd_ret = client.cmd_iter(
            host,
            'lxc.{0}'.format(fun),
            [name],
            kwarg={'path': path},
            timeout=60)
    data = next(cmd_ret)
    data = data.get(host, {}).get('ret', None)
    if data:
        data = {host: data}
    return data
213203
function ZNV2Swarm (opt, protocol, zeronet, lp2p) {
  const self = this
  self.proto = self.protocol = new ZProtocol({
    crypto: opt.crypto,
    id: opt.id
  }, zeronet)

  log('creating zeronet swarm')

  const tr = self.transport = {}
  self.multiaddrs = (opt.listen || []).map(m => multiaddr(m));

  (opt.transports || []).forEach(transport => {
    tr[transport.tag || transport.constructor.name] = transport
    if (!transport.listeners) {
      transport.listeners = []
    }
  })

  TRANSPORT(self)
  DIAL(self, lp2p)

  self.advertise = {
    ip: null,
    port: null,
    port_open: null
  }

  let nat
  if (opt.nat) nat = self.nat = new NAT(self, opt)

  self.start = cb => series([
    self.listen,
    nat ? nat.doDefault : cb => cb()
  ], cb)

  self.stop = cb => series([
    self.unlisten
  ], cb)
}
767083
private static void setSnmpInfo(SnmpType snmpType) {
        if (snmpType == null || !snmpType.isEnabled()) {
            return;
        }
        //Validate Snmp Configuration.
        if (snmpType.getTarget() == null || snmpType.getTarget().trim().length() == 0) {
            throw new IllegalArgumentException("Target must be specified for SNMP configuration.");
        }
        if (snmpType.getAuthkey() != null && snmpType.getAuthkey().length() < 8) {
            throw new IllegalArgumentException("SNMP Authkey must be > 8 characters.");
        }
        if (snmpType.getPrivacykey() != null && snmpType.getPrivacykey().length() < 8) {
            throw new IllegalArgumentException("SNMP Privacy Key must be > 8 characters.");
        }
    }
406565
def from_payload(self, payload):
        """"""
        self.session_id = payload[0]*256 + payload[1]
        self.status_id = payload[2]
        self.index_id = payload[3]
        self.node_parameter = payload[4]
        self.parameter_value = payload[5]*256 + payload[6]
1140913
def _walk_factory(self, dep_predicate):
    """"""
    walk = None
    if dep_predicate:
      walk = self.DepPredicateWalk(dep_predicate)
    else:
      walk = self.NoDepPredicateWalk()
    return walk
1067191
def get_snmp_information(self):
        """"""

        # Default values
        snmp_dict = {
            'chassis_id': '',
            'location': '',
            'contact': '',
            'community': {}
        }

        commands = [
            'show snmp chassis',
            'show snmp location',
            'show snmp contact'
        ]
        snmp_config = self.device.run_commands(commands, encoding='json')
        for line in snmp_config:
            for k, v in line.items():
                if k == 'chassisId':
                    snmp_dict['chassis_id'] = v
                else:
                    # Some EOS versions add extra quotes
                    snmp_dict[k] = v.strip('"')

        commands = ['show running-config | section snmp-server community']
        raw_snmp_config = self.device.run_commands(commands, encoding='text')[0].get('output', '')
        for line in raw_snmp_config.splitlines():
            match = self._RE_SNMP_COMM.search(line)
            if match:
                matches = match.groupdict('')
                snmp_dict['community'][match.group('community')] = {
                    'acl': py23_compat.text_type(matches['v4_acl']),
                    'mode': py23_compat.text_type(matches['access'])
                }

        return snmp_dict
829153
def check_snmp(self):
        """"""
        # Import the SNMP client class
        from glances.snmp import GlancesSNMPClient

        # Create an instance of the SNMP client
        clientsnmp = GlancesSNMPClient(host=self.args.client,
                                       port=self.args.snmp_port,
                                       version=self.args.snmp_version,
                                       community=self.args.snmp_community,
                                       user=self.args.snmp_user,
                                       auth=self.args.snmp_auth)

        # If we cannot grab the hostname, then exit...
        ret = clientsnmp.get_by_oid("1.3.6.1.2.1.1.5.0") != {}
        if ret:
            # Get the OS name (need to grab the good OID...)
            oid_os_name = clientsnmp.get_by_oid("1.3.6.1.2.1.1.1.0")
            try:
                self.system_name = self.get_system_name(oid_os_name['1.3.6.1.2.1.1.1.0'])
                logger.info("SNMP system name detected: {}".format(self.system_name))
            except KeyError:
                self.system_name = None
                logger.warning("Cannot detect SNMP system name")

        return ret