def do_kv_store_get(key_name): try: (code, value) = get_opsbro_local('/kv/%s' % key_name) except get_request_errors() as exp: logger.error('Cannot join opsbro agent for info: %s' % exp) sys.exit(1) if code == 404: cprint('ERROR: the key %s does not exist' % key_name, color='red') sys.exit(2) value = bytes_to_unicode(value) cprint("%s::%s" % (key_name, value))
def __init__(self, data): self.data = data self.domain = '' t = (byte_to_int(data[2]) >> 3) & 15 # Opcode bits if t == 0: # Standard query ini = 12 lon = byte_to_int(data[ini]) while lon != 0: self.domain += bytes_to_unicode( data[ini + 1:ini + lon + 1]) + '.' ini += lon + 1 lon = byte_to_int(data[ini])
def test_encryption(self): orig_test = 'Hi I am Alice' RSA = encrypter.get_RSA() encrypted = RSA.encrypt(unicode_to_bytes(orig_test), self.mfkey_pub) # encrypted thanks to public decrypted = bytes_to_unicode(RSA.decrypt( encrypted, self.mfkey_priv)) # decrypte with private print('Original:%s(%s)\nDecrypted:%s(%s)' % (orig_test, type(orig_test), decrypted, type(decrypted))) self.assert_(decrypted == orig_test) self.assert_(encrypted != orig_test) print('OK')
def _get_expr_evaluator(expr): expr = bytes_to_unicode(expr) this_expr = expr def _get_value_from_expression(): logger.debug('\n\n\n\n\n\n\n\n\n\nEVAL EXPR %s\n\n' % this_expr) expr_64 = base64.b64encode(unicode_to_bytes(this_expr)) try: r = post_opsbro_json('/agent/evaluator/eval', {'expr': expr_64}) except Exception as exp: logger.debug('\n\n\n\n\n\n\n\n\n\nExcep Result %s => %s\n\n' % (this_expr, exp)) r = None logger.debug('\n\n\n\n\n\n\n\nResult %s => %s\n\n' % (this_expr, r)) return r return _get_value_from_expression
def do_exec(group='*', cmd='uname -a'): if cmd == '': logger.error('Missing command') return # The information is available only if the agent is started wait_for_agent_started(visual_wait=True) cmd_64 = bytes_to_unicode(base64.b64encode(unicode_to_bytes(cmd))) try: r = get_opsbro_json('/exec/%s?cmd=%s' % (group, cmd_64)) except get_request_errors() as exp: cprint('ERROR: cannot launch the command: %s' % exp, color='red') sys.exit(2) cid = r print("Command group launch as cid", cid) time.sleep(5) # TODO: manage a real way to get the result.. try: r = get_opsbro_json('/exec-get/%s' % cid) except get_request_errors() as exp: cprint('ERROR: cannot get execution results: %s' % exp, color='red') sys.exit(2) res = r['res'] print('Launched at: %s' % res) for (uuid, e) in res.items(): node = e['node'] nname = node['name'] color = {'alive': 'green', 'dead': 'red', 'suspect': 'yellow', 'leave': 'cyan'}.get(node['state'], 'cyan') cprint(nname, color=color) cprint('Return code for [%s]:' % e['cmd'], end='') color = {0: 'green', 1: 'yellow', 2: 'red'}.get(e['rc'], 'cyan') cprint(e['rc'], color=color) cprint('Output:', end='') cprint(e['output'].strip(), color=color) if e['err']: cprint('Error:', end='') cprint(e['err'].strip(), color='red') cprint('')
def stopping_agent(self): enabled = self.get_parameter('enabled') if not enabled: return groups = gossiper.groups # no need to copy, the group pointer is in read only self.logger.info( 'Pushing back ours groups and discovery informations to Shinken Enterprise' ) collectors_data = {} for (ccls, e) in collectormgr.collectors.items(): cname, c = collectormgr.get_collector_json_extract(e) collectors_data[cname] = c # In groups=> templates, we do not want : and . in the names _mapping = {':': '--', '.': '--'} use_value = ','.join(groups) for (k, v) in _mapping.items(): use_value = use_value.replace(k, v) payload = { '_AGENT_UUID': gossiper.uuid, 'use': use_value, } # System info system_results = collectors_data.get('system', {}).get('results', {}) hostname = system_results.get('hostname', '') payload['host_name'] = hostname fqdn = system_results.get('fqdn', '') if fqdn: payload['_FQDN'] = fqdn publicip = system_results.get('publicip', '') if publicip: payload['_PUBLIC_IP'] = publicip # which address to use in fact? # how to choose: fqdn > public_ip > hostname if fqdn: payload['address'] = fqdn elif publicip: payload['address'] = publicip else: payload['address'] = hostname # Timezone timezone = collectors_data.get('timezone', {}).get('results', {}).get('timezone', '') if timezone: payload['_TIMEZONE'] = bytes_to_unicode(timezone) cpucount = system_results.get('cpucount', '') if cpucount: payload['_CPU_COUNT'] = str(cpucount) # data must be string linux_distribution = system_results.get('os', {}).get('linux', {}).get( 'distribution', '') if linux_distribution: payload['_LINUX_DISTRIBUTION'] = linux_distribution # Memory physical_memory = collectors_data.get('timezone', {}).get( 'results', {}).get('phys_total', '') if physical_memory: payload['_PHYSICAL_MEMORY'] = physical_memory # Network try: network_interfaces = ','.join( collectors_data.get('interfaces', {}).get('results', {}).keys()) except AttributeError: # was without interfaces network_interfaces = '' if network_interfaces: payload['_NETWORK_INTERFACES'] = network_interfaces # Geoloc (lat and long) try: geoloc = collectors_data.get('geoloc', {}).get('results', {}).get('loc', '') except AttributeError: # was without interfaces geoloc = '' if geoloc and geoloc.count(',') == 1: lat, long = geoloc.split(',', 1) payload['_LAT'] = lat payload['_LONG'] = long # disks try: volumes = ','.join( collectors_data.get('diskusage', {}).get('results', {}).keys()) except AttributeError: volumes = '' if volumes: payload['_VOLUMES'] = volumes file_result = self.get_parameter('file_result') self.logger.info('Writing file result to : %s' % file_result) if file_result: f = open(file_result, 'w') f.write(jsoner.dumps(payload, indent=4)) f.close()