def main(): try: args = _handle_args() config = _parse_config(args.config_file) verify_interval, _ = _handle_global_config(config) host, port = _handle_bigip_config(config) # FIXME (kenr): Big-IP settings are currently static (we ignore any # changes to these fields in subsequent updates). We # may want to make the changes dynamic in the future. # BIG-IP to manage bigip = ManagementRoot( host, config['bigip']['username'], config['bigip']['password'], port=port, token="tmos") k8s_managers = [] for partition in config['bigip']['partitions']: # Management for the BIG-IP partitions manager = K8sCloudServiceManager( bigip, partition, schema_path=SCHEMA_PATH) k8s_managers.append(manager) handler = ConfigHandler(args.config_file, k8s_managers, verify_interval) if os.path.exists(args.config_file): handler.notify_reset() watcher = ConfigWatcher(args.config_file, handler.notify_reset) watcher.loop() handler.stop() except (IOError, ValueError, ConfigError) as e: log.error(e) sys.exit(1) except Exception: log.exception('Unexpected error') sys.exit(1) return 0
def main(*args): mgmt = ManagementRoot(BIGIP_MNG_IP, BIGIP_USER, BIGIP_PASSWORD) print(args[0][1]) ###hook logic -- arguments from the config file, passed to the hook script if args[0][1] == "deploy_challenge": deploy_challenge(mgmt, BIGIP_CERTBOT_VERIFICATION_VS_NAME, BIGIP_CERTBOT_VERIFICATION_VS_IP, BIGIP_PARTITION, BIGIP_VLAN, sys_vars) elif args[0][1] == "clean_challenge": clean_challenge(mgmt, BIGIP_CERTBOT_VERIFICATION_VS_NAME, BIGIP_PARTITION) elif args[0][1] == "deploy_cert": f5_cert_deployer(mgmt, BIGIP_SSL_VS_NAME, BIGIP_SSL_VS_IP, BIGIP_PARTITION, BIGIP_VLAN, BIGIP_HTTP_PROFILE, BIGIP_SSL_PROFILE, BIGIP_SSL_VS_PORT, sys_vars)
def api(self): if self._client: return self._client try: result = ManagementRoot(self.provider['server'], self.provider['user'], self.provider['password'], port=self.provider['server_port'], verify=self.provider['validate_certs'], token='tmos') self._client = result return self._client except Exception as ex: error = 'Unable to connect to {0} on port {1}. The reported error was "{2}".'.format( self.provider['server'], self.provider['server_port'], str(ex)) raise F5ModuleError(error)
def test_default(host): vars = host.ansible.get_variables() vault_pass = open("../../molecule/.vault_pass", "r").read().replace("\n", "") vault = Vault(vault_pass) decrypted_host = vault.load(vars["ansible_host"]["__ansible_vault"]) decrypted_user = vault.load(vars["http_user"]["__ansible_vault"]) decrypted_pass = vault.load(vars["http_pass"]["__ansible_vault"]) mgmt = ManagementRoot(decrypted_host, decrypted_user, decrypted_pass) dg = mgmt.tm.cm.device_groups.device_group.load(name="my_device_group") assert dg.name == "my_device_group" assert dg.description == "My device group" devices = dg.devices_s.get_collection() assert len(devices) == 1 decrypted_device_name = vault.load(vars["device_name"]["__ansible_vault"]) assert devices[0].name == decrypted_device_name
def del_irdg_ajax(active_ltm, irDgName, irOrDg, dgType): #'DevIP' 'IrDgName' 'IrType' 'IrCode' 'IrDgType' 'IrDgData' logger.info("del_irdg_ajax.py parms\n DevIP: " + active_ltm + "\niRule/Data Group Name: " + irDgName + "\nConfig Type: " + irOrDg + "\nDG Type: " + dgType + "\n") admpass = getpass.getpass('LTM', 'admin') mr = ManagementRoot(str(active_ltm), 'admin', admpass) idx = 1 strReturn = {str(idx): 'iRule/Data Group Deletion Report'} idx += 1 #Update a iRule/Data Group configuration try: if irOrDg == "iRule": loaded_ir = mr.tm.ltm.rules.rule.load(name=irDgName) loaded_ir.delete() elif irOrDg == "Data Group": loaded_dg = mr.tm.ltm.data_group.internals.internal.load( name=irDgName) loaded_dg.delete() except Exception as e: logger.info("iRule/Data Group Deletion Exception") strReturn[str( idx )] = "iRule/Data Group Deletion Exception fired! (" + irDgName + "): " + str( e) idx += 1 logger.info( "Exception during iRule/Data Group Deletion has been fired: " + str(e)) logger.info(traceback.format_exc()) return json.dumps(strReturn) strReturn[str( idx )] = irOrDg + " iRule/Data Group (" + irDgName + ") deletion has been completed successfully" idx += 1 logger.info("iRule/Data Group deletion has been completed successfully") for keys, values in strReturn.items(): logger.info("Key: " + keys + " Value: " + values) return json.dumps(strReturn)
def new_snatpool_build(active_ltm, snat_name, snat_addresses): admpass = getpass.getpass('LTM', 'admin') mr = ManagementRoot(str(active_ltm), 'admin', admpass) # Check if Standard naming is used useGlobalNaming = loadStdNames.useStdNaming() logger.info("new_snatpool_build()- Use Standard Global naming : " + useGlobalNaming) idx = 1 strReturn = {str(idx): 'Snatpool Creation Report'} idx += 1 if useGlobalNaming == '1': snat_name = loadStdNames.get_std_name(active_ltm, 'LOCAL', 'SNAT_POOL', '', snat_name) logger.info( str(active_ltm) + " Snatpool DNS:" + str(snat_name) + " Snatpool DEST:" + str(snat_addresses)) logger.info( "Snatpool Creation process has been initiated. Snatpool Name: " + snat_name) try: snat_members = [] for aMember in snat_addresses.split(':'): snat_members.append(aMember) mysnat = mr.tm.ltm.snatpools.snatpool.create(name=snat_name, members=snat_members) strReturn[str( idx )] = 'Snatpool (' + snat_name + ') has been succssfully created' idx += 1 except Exception as e: logger.info("Exception during Snatpool creation") strReturn[str(idx)] = "Exception fired!: " + str(e) idx += 1 return json.dumps(strReturn) return json.dumps(strReturn)
def _init_vcmp_hosts(self): '''Initialize the data structures for vCMP Hosts and their Guests.''' vcmp_hostnames = self.driver.conf.icontrol_vcmp_hostname.split(',') for vcmp_hostname in vcmp_hostnames: vcmp_host = {} vcmp_host['bigip'] = ManagementRoot( vcmp_hostname, self.driver.conf.icontrol_username, self.driver.conf.icontrol_password) vcmp_host['guests'] = [] try: guests = list( vcmp_host['bigip'].tm.vcmp.guests.get_collection()) except iControlUnexpectedHTTPError as ex: if ex.response.status_code == 400 and \ 'One of the following features must be licensed/' \ 'provisioned for the URI vcmp : vcmp' in ex.message: msg = 'VcmpManager::_init_vcmp_hosts: Given vCMP host {0} ' \ 'is not licensed for vCMP. Device returned exception: ' \ '{1}'.format(vcmp_hostname, ex) raise BigIPNotLicensedForVcmp(msg) else: raise(ex) except Exception as ex: raise(ex) for guest in guests: if utils.strip_cidr_netmask( guest.managementIp) in self.driver.get_bigip_hosts(): vcmp_host['guests'].append(guest) self.vcmp_hosts.append(vcmp_host) self._check_vcmp_host_assignments() for vcmp_host in self.vcmp_hosts: for vcmp_guest in vcmp_host['guests']: LOG.debug(('VcmpManager::_init_vcmp_hosts: vCMPHost[%s] ' 'vCMPGuest[%s] - mgmt: %s' % ( vcmp_host['bigip'].hostname, vcmp_guest.name, utils.strip_cidr_netmask( vcmp_guest.managementIp))))
def add_rule(): form = EditorForm(request.form) b = ManagementRoot(session['host'], session['uname'], session['upass']) # Add form validation!! if request.method == 'POST': rule_name = request.form['rule_name'] rule_partition = request.form['rule_partition'] rule_body = request.form['rule_body'].replace('\r\n', '\\r\\n') if not b.tm.ltm.rules.rule.exists(name=rule_name, partition=rule_partition): r1 = b.tm.ltm.rules.rule.create(name=rule_name, partition=rule_partition, apiAnonymous=rule_body) flash('Rule created', 'success') return redirect(url_for('rules')) else: flash('Rule already exists, try another name', 'info') return redirect(url_for('add_rule')) return render_template('add_rule.html', form=form, host=b.hostname)
def handler(context, inputs): mgmt = ManagementRoot("192.168.110.171", "admin", "vmware1!vmware1!") # capturar nome do pool escrita no form nomePool = inputs['requestInputs']['nomeDoPool'] # capturar metodo de modoBalanceamento modoBalanceamento = inputs['requestInputs']['algoritmoLb'] # capturando a descricao do pool inserida no form descricaoPool = inputs['requestInputs']['poolDescription'] # criar pool virtualPool = mgmt.tm.ltm.pools.pool.create(name=nomePool, partition='Common') virtualPool.description = descricaoPool virtualPool.loadBalancingMode = modoBalanceamento virtualPool.update()
def my_form_post(): if not session.get('logged_in'): return redirect(url_for('login')) x = str(session.get('user', None)) y = str(session.get('pass', None)) z = str(session.get('part', None)) w = str(session.get('wideip', None)) v = str(session.get('ip',None)) mgmt = ManagementRoot(v, x, y) pool = mgmt.tm.gtm.wideips.a_s.a.load(partition=z, name=w) c=pool.pools[0].get('ratio') d=pool.pools[1].get('ratio') b=pool.persistence if b == 'enabled': e = pool.ttlPersistence f = pool.persistCidrIpv4 return render_template('D:/join1.html', variable4=e, variable5=f, variable6=c, variable7=d, variable8=b) if b == 'disabled': return render_template('D:/join.html', variable6=c, variable7=d)
def api(self): if self._client: return self._client for x in range(0, 10): try: result = ManagementRoot(self.params['server'], self.params['user'], self.params['password'], port=self.params['server_port'], verify=self.params['validate_certs'], token='tmos') self._client = result return self._client except Exception: time.sleep(3) raise F5ModuleError('Unable to connect to {0} on port {1}. ' 'Is "validate_certs" preventing this?'.format( self.params['server'], self.params['server_port']))
def load_irdg_names(active_ltm, irType, irDgPart): #'DevIP' 'IrType' 'IrDgPart' logger.info("load_irdg_names.py parms\n DevIP: " + active_ltm + "\niRule or Data Group: " + irType + "\nPartition: " + irDgPart + "\n") admpass = getpass.getpass('LTM', 'admin') mr = ManagementRoot(str(active_ltm), 'admin', admpass) strReturn = '' logger.info("iRule/Data Group Modification process has been initiated.") #Create a iRule/Data Group try: if irType == "iRule": ir_list = mr.tm.ltm.rules.get_collection() i=0 ir_list_len = len(ir_list)-1 for air in ir_list: if ir_list_len != i: strReturn += air.name + '|' else: strReturn += air.name i = i+1 elif irType == "Data Group": dg_list = mr.tm.ltm.data_group.internals.get_collection() i=0 dg_list_len = len(dg_list)-1 for adg in dg_list: if dg_list_len != i: strReturn += adg.name + '|' else: strReturn += adg.name i = i+1 except Exception as e: logger.info("iRule/Data Group Exception - Retrieving iRule/Data Group names") logger.info("Error Details: " + str(e)) return json.dumps(strReturn) logger.info("Retrieved names: " + strReturn) logger.info("Name retrieving for iRule/Data Group has been completed") return json.dumps(strReturn)
def deviceFunction(): global activeLTM with open("device_list.txt", "rb") as DeviceList: for device in DeviceList: device = device.strip() mgmt = ManagementRoot(device, user, pwd, verify=False) print "Connection to " + device + " successful!" ltmSys = mgmt.tm.cm.devices.get_collection() # above api call will return both active and standby device information in the form of list type object. # index 0 will be one from where api call has been intiated if str(ltmSys[0].failoverState) == 'active': #activeLTM.append(str(ltmSys[0].managementIp)) activeLTM[str(ltmSys[0].hostname)] = str( ltmSys[0].managementIp) else: #activeLTM.append(str(ltmSys[1].managementIp)) activeLTM[str(ltmSys[1].hostname)] = str( ltmSys[1].managementIp) print activeLTM
def poll_for_licensed_bigip( bigip_ip, username, password, bigip_ver, ifc_num, attempts=50, interval=10 ): '''Poll the device until it is licensed and has a config.''' for attempt in range(attempts): time.sleep(interval) try: bigip = ManagementRoot(bigip_ip, username, password) registration = bigip.tm.shared.licensing.registration.load() assert registration.licensedVersion == bigip_ver assert len(bigip.tm.net.vlans.get_collection()) == ifc_num - 1 assert len(bigip.tm.net.interfaces.get_collection()) == ifc_num assert len(bigip.tm.net.selfips.get_collection()) == \ ifc_num - 1 return bigip except Exception as ex: if attempt == (attempts - 1): raise ex continue
def parse_config(config_file): config = ConfigParser.ConfigParser() config.readfp(open(config_file)) bigips = [] try: config_addrs = config.get("DEFAULT", 'icontrol_hostname') config_user = config.get("DEFAULT", 'icontrol_username') config_pass = config.get("DEFAULT", 'icontrol_password') except ConfigParser.NoOptionError as err: print(err.message) return bigips for config_addr in config_addrs.split(','): bigips.append( ManagementRoot(hostname=config_addr, username=config_user, password=config_pass)) return bigips
def handler(context, inputs): mgmt = ManagementRoot("192.168.110.171", "admin", "vmware1!vmware1!") poolName = inputs['customProperties']['nomeDoPool'] servico = inputs['customProperties']['portaServico'] print(poolName) pool_obj = mgmt.tm.ltm.pools.pool poolAtual = pool_obj.load(partition='Common', name=poolName) print(poolAtual) members = poolAtual.members_s member = poolAtual.members_s.members ip = inputs['addresses'][0][0] + ":" + str(servico) m1 = poolAtual.members_s.members.create(partition='Common', name=ip) m1 = poolAtual.members_s.members.load(partition='Common', name=ip)
def main(): global VS global HOST parser = argparse.ArgumentParser(description='') parser.add_argument('-a', '--address', required=True) parser.add_argument('-p', '--partition', required=True) parser.add_argument('-o', '--output', required=True) args = parser.parse_args() Conf.mgt = ManagementRoot(args.address, USER, PASS, token=True) # load data group lists first (proxypass lookup) load_datagroup_list(args.partition) # load all VirtualServer objects for vs in list_all_vs(partition=args.partition): VS.append(VirtualServer(vs)) graphme(args.partition, args.output)
def load_irdg_config(active_ltm, irType, irDgName): #'DevIP' 'IrType' 'IrDgPart' logger.info("load_irdg_config.py parms\n DevIP: " + active_ltm + "\niRule or Data Group: " + irType + "\nName: " + irDgName + "\n") admpass = getpass.getpass('LTM', 'admin') mr = ManagementRoot(str(active_ltm), 'admin', admpass) dictReturn = {'name': ''} logger.info("iRule/Data Group Modification process has been initiated.") #Load a iRule/Data Group configuration try: if irType == "iRule": dictReturn["IrOrDg"] = irType ir_list = mr.tm.ltm.rules.get_collection() for aIR in ir_list: if aIR.name == irDgName: dictReturn["name"] = aIR.name dictReturn["apiAnonymous"] = aIR.apiAnonymous elif irType == "Data Group": dictReturn["IrOrDg"] = irType dg_list = mr.tm.ltm.data_group.internals.get_collection() for aDG in dg_list: if aDG.name == irDgName: dictReturn["name"] = aDG.name dictReturn["type"] = aDG.type # 'records' value is a list with dictinary type value. e.g records = [{'data': 'HTTPS', 'name': 'HTTP'}, {'data': 'World', 'name': 'Hello'}] dictReturn["records"] = aDG.records except Exception as e: logger.info( "iRule/Data Group Exception - Retrieving iRule/Data Group configuration" ) logger.info("Error Details: " + str(e)) logger.info(traceback.format_exc()) return json.dumps(dictReturn) logger.info("Name retrieving for iRule/Data Group has been completed") return json.dumps(dictReturn)
def getPrfSettings(active_ltm, prfType, parPrfName, prfMode): logger.info('Called getPrfSettings(): %s %s %s %s' % (active_ltm, prfType, parPrfName, prfMode)) admpass = getpass.getpass('LTM', 'admin') mr = ManagementRoot(str(active_ltm), 'admin', admpass) output = {} logger.info('getPrfSettings.py getPrfSettings() - Loading ' + prfType + ' Profile Settings\n') if prfType == "DNS": output = getDnsPrfSettings(mr, parPrfName, prfMode) elif prfType == "Cookie": output = getCookiePrfSettings(mr, parPrfName, prfMode) elif prfType == "DestAddrAffinity": output = getDstAffSettings(mr, parPrfName, prfMode) elif prfType == "SrcAddrAffinity": output = getSrcAffSettings(mr, parPrfName, prfMode) elif prfType == "Hash": output = getHashSettings(mr, parPrfName, prfMode) elif prfType == "SSL": output = getSSLSettings(mr, parPrfName, prfMode) elif prfType == "Universal": output = getUniSettings(mr, parPrfName, prfMode) elif prfType == "FastL4": output = getF4Settings(mr, parPrfName, prfMode) elif prfType == "TCP": output = getTcpSettings(mr, parPrfName, prfMode) elif prfType == "UDP": output = getUdpSettings(mr, parPrfName, prfMode) elif prfType == "CLIENTSSL": output = getClisslSettings(mr, parPrfName, prfMode) elif prfType == "SERVERSSL": output = getSrvsslSettings(mr, parPrfName, prfMode) elif prfType == "OneConnect": output = getOCSettings(mr, parPrfName, prfMode) elif prfType == "Stream": output = getStreamSettings(mr, parPrfName, prfMode) return output
def test_default(host): vars = host.ansible.get_variables() vault_pass = open("../../molecule/.vault_pass", "r").read().replace("\n", "") vault = Vault(vault_pass) decrypted_host = vault.load(vars["ansible_host"]["__ansible_vault"]) decrypted_user = vault.load(vars["http_user"]["__ansible_vault"]) decrypted_pass = vault.load(vars["http_pass"]["__ansible_vault"]) mgmt = ManagementRoot(decrypted_host, decrypted_user, decrypted_pass) decrypted_device_name = vault.load(vars["device_name"]["__ansible_vault"]) decrypted_device_internal_ip = vault.load( vars["device_internal_ip"]["__ansible_vault"]) device = mgmt.tm.cm.devices.device.load(name=decrypted_device_name) assert device.name == decrypted_device_name assert device.comment == "My lab device" assert device.configsyncIp == decrypted_device_internal_ip assert device.contact == "admin@localhost" assert device.description == "My device" assert device.haCapacity == 10 assert device.location == "Central Office"
def api(self): ex = None if self._client: return self._client for x in range(0, 3): try: result = ManagementRoot(self.params['server'], self.params['user'], self.params['password'], port=self.params['server_port'], verify=self.params['validate_certs'], token='tmos') self._client = result return self._client except Exception as ex: time.sleep(1) error = 'Unable to connect to {0} on port {1}.'.format( self.params['server'], self.params['server_port']) if ex is not None: error += ' The reported error was "{0}".'.format(str(ex)) raise F5ModuleError(error)
def get_ltmobj_names(active_ltm, obj_type): #logger.info('Called get_profiles(): %s %s' % (dev_ip, obj_type)) admpass = getpass.getpass('LTM', 'admin') mr = ManagementRoot(str(active_ltm), 'admin', admpass) output = '' ''' Retrive the name list of a given object type from the given LTM Suppported Object types 1. VS - Virtual Server 2. POOL - Pool name 3. MONITOR - Monitor name ''' logger.info('Object Types: %s' % obj_type) if obj_type == "VS": output = get_vs_names(mr) elif obj_type == "POOL": output = get_pool_names(mr) logger.info('output in get_ltmobj_names: %s' % output) return output
def test_default(host): vars = host.ansible.get_variables() vault_pass = open("../../molecule/.vault_pass", "r").read().replace("\n", "") vault = Vault(vault_pass) decrypted_host = vault.load(vars["ansible_host"]["__ansible_vault"]) decrypted_user = vault.load(vars["http_user"]["__ansible_vault"]) decrypted_pass = vault.load(vars["http_pass"]["__ansible_vault"]) mgmt = ManagementRoot(decrypted_host, decrypted_user, decrypted_pass) user = mgmt.tm.auth.users.user.load(name="user1") assert user.name == "user1" assert user.description == "User 1" partition_access = [ {"name": "Common", "role": "guest"}, {"name": "Test", "role": "operator"}, ] assert not DeepDiff( partition_access, user.partitionAccess, exclude_regex_paths={r"root\[\d+\]\['nameReference'\]"}, )
def do_something1(text1,text2,text3,text4,text5): x = str(session.get('user', None)) y = str(session.get('pass', None)) z = str(session.get('part', None)) w = str(session.get('wideip', None)) v = str(session.get('ip',None)) text1 = int(text1) text2 = int(text2) text3 = str(text3) text4 = int(text4) text5 = int(text5) mgmt = ManagementRoot(v, x, y) pool = mgmt.tm.gtm.wideips.a_s.a.load(partition=z, name=w) pool.pools[0].update({'ratio': text1}) pool.pools[1].update({'ratio': text2}) pool.persistence = text3 if pool.persistence == 'enabled': pool.ttlPersistence = text4 pool.persistCidrIpv4 = text5 pool.update() return redirect(url_for('account'))
def upload_cert_key_to_nlb(helper, options, cert, key): # Generate filenames key_filename = options['fqdn'] + '.key' cert_filename = options['fqdn'] + '.crt' # Upload key try: helper.event('upload_key', 'Uploading key to load balancer ' + options['nlb']['hostname']) bigip = ManagementRoot(options['nlb']['hostname'], options['nlb']['username'], options['nlb']['password']) bigip.shared.file_transfer.uploads.upload_bytes(key, key_filename) param_set = {'name': key_filename, 'partition': options['nlb']['partition'], 'from-local-file': '/var/config/rest/downloads/' + key_filename} bigip.tm.sys.crypto.keys.exec_cmd('install', **param_set) helper.end_event(description='Uploaded key to load balancer ' + options['nlb']['hostname']) helper.event('upload_cert', 'Uploading certificate to load balancer ' + options['nlb']['hostname']) bigip.shared.file_transfer.uploads.upload_bytes(cert, cert_filename) param_set = {'name': cert_filename, 'partition': options['nlb']['partition'], 'from-local-file': '/var/config/rest/downloads/' + cert_filename} bigip.tm.sys.crypto.certs.exec_cmd('install', **param_set) helper.end_event(description='Uploaded certificate to load balancer ' + options['nlb']['hostname']) except Exception as e: helper.end_event(description='Error uploading data to load balancer: ' + str(e), success=False)
def test_default(host): vars = host.ansible.get_variables() vault_pass = open("../../molecule/.vault_pass", "r").read().replace("\n", "") vault = Vault(vault_pass) decrypted_host = vault.load(vars["ansible_host"]["__ansible_vault"]) decrypted_user = vault.load(vars["http_user"]["__ansible_vault"]) decrypted_pass = vault.load(vars["http_pass"]["__ansible_vault"]) mgmt = ManagementRoot(decrypted_host, decrypted_user, decrypted_pass) policy = mgmt.tm.auth.password_policy.load() assert policy.expirationWarning == 5 assert policy.maxDuration == 90 assert policy.maxLoginFailures == 3 assert policy.minDuration == 30 assert policy.minimumLength == 8 assert policy.passwordMemory == 1 assert policy.policyEnforcement == "enabled" assert policy.requiredLowercase == 2 assert policy.requiredNumeric == 1 assert policy.requiredSpecial == 1 assert policy.requiredUppercase == 2
def edit_rule(name): partition, name = name.split('~') b = ManagementRoot(session['host'], session['uname'], session['upass']) rule = b.tm.ltm.rules.rule.load(name=name, partition=partition) form = EditorForm(request.form) form.rule_name.data = rule.name form.rule_partition.data = rule.partition form.rule_body.data = rule.apiAnonymous # Add form validation!! if request.method == 'POST': rule_name = request.form['rule_name'] rule_partition = request.form['rule_partition'] rule_body = request.form['rule_body'] # Set attributes on BIG-IP object and update r1 = b.tm.ltm.rules.rule.load(name=rule_name, partition=rule_partition) r1.apiAnonymous = rule_body r1.update() flash('Rule updated', 'success') return redirect(url_for('rules')) return render_template('edit_rule.html', form=form, host=b.hostname)
def load_snatpool_names(active_ltm): admpass = getpass.getpass('LTM', 'admin') mr = ManagementRoot(str(active_ltm), 'admin', admpass) strReturn = [] logger.info("Snatpool Name loading process has been initiated.") try: snatp_list = mr.tm.ltm.snatpools.get_collection() for aSnat in snatp_list: strReturn.append(aSnat.name) strReturn.append(aSnat.partition) except Exception as e: logger.info("Exception during collecting Snatpool names") logger.info(str(e)) strReturn.append("FAIL") strReturn.append(str(e)) return json.dumps(strReturn) return json.dumps(strReturn)
def check(args): logging.debug("[x] Connecting to F5..") mgmt = ManagementRoot(args.f5.ip, args.f5.user, args.f5.password) logging.debug(" [-] Connected.") logging.debug("[x] Fetching all certificates..") certs = mgmt.tm.sys.file.ssl_certs.get_collection() logging.debug(" [-] Done.") logging.debug("[x] Processing expiration time..") for cert in certs: verify_cert(cert, args.warning, args.critical) output = "" alert = False if len(CRITICAL): alert = True output += "CRITICAL: {} certificates are going to expire.".format( len(CRITICAL) + len(WARNING)) elif len(WARNING): alert = True output += "WARNING: {} certificates are going to expire.".format( len(WARNING)) if alert: output += " Following certificates are raising the threshold: {}".format( ", ".join([ "{} ({})".format(x.name, datetime.fromtimestamp(int(x.expirationDate))) for x in WARNING + CRITICAL ])) if not len(WARNING) and not len(CRITICAL): print("OK") sys.exit(0) print(output) if len(CRITICAL): sys.exit(2) sys.exit(1)
def __init__(self, *args, **kwargs): if not HAS_F5SDK: raise F5ModuleError("The python f5-sdk module is required") if kwargs['state'] != 'absent': if not kwargs['content'] and not kwargs['src']: raise F5ModuleError( "Either 'content' or 'src' must be provided") source = kwargs['src'] if source: with open(source) as f: kwargs['content'] = f.read() # The params that change in the module self.cparams = dict() # Stores the params that are sent to the module self.params = kwargs self.api = ManagementRoot(kwargs['server'], kwargs['user'], kwargs['password'], port=kwargs['server_port'])