async def device_info(hostname: str, **api_options): async with IPFabricClient() as ipf: filter_hostname = IPFabricClient.parse_filter(f"hostname = {hostname}") inventory_task = ipf.fetch_devices(filters=filter_hostname, **api_options) parts_task = ipf.fetch_device_parts(filters=filter_hostname, **api_options) interfaces_task = fetch_device_interfaces(ipf, filters=filter_hostname, **api_options) vlans_task = fetch_device_vlans(ipf, filters=filter_hostname, **api_options) ipaddrs_task = fetch_device_ipaddrs(ipf, filters=filter_hostname, **api_options) results = await asyncio.gather( inventory_task, parts_task, interfaces_task, vlans_task, ipaddrs_task, return_exceptions=True, ) return results
async def example(site, **options): ipf = IPFabricClient() await ipf.login() return await ipf.fetch_devices( filters=ipf.parse_filter(f"siteName = {site}"), **options)
async def example(**options): """ Fetch all of the devices with uptime out of compliance. Other Parameters ---------------- options: dict Request options as allowed for by the table_api decorator. Returns ------- By default the list of found records, or empty-list. """ ipf = IPFabricClient() await ipf.login() columns = [ "hostname", "siteName", "uptime", "vendor", "family", "platform", "model", "version", ] res = await fetch_device_uptime(ipf, columns=columns, **options) await ipf.api.aclose() return res
def device_info(ipf: IPFabricClient, hostname: str, **api_options) -> Coroutine: """ This function returns a coroutine that is responsible for obtaining device information for a given `hostname` and returns a dictionary of data representing each aspect of the device: hostname: the device hostname facts: the device inventory record parts: the device parts records interfaces: the device interface records vlans: the vlan used by this device ipaddrs: the IP addresses assigned to the device Parameters ---------- ipf: IPFabricClient hostname: device hostname api_options: Returns ------- Coroutine, when awaited will return the dictionary as described. """ filter_hostname = IPFabricClient.parse_filter(f"hostname = {hostname}") fut = asyncio.gather( ipf.fetch_devices(filters=filter_hostname, **api_options), ipf.fetch_device_parts(filters=filter_hostname, **api_options), fetch_device_interfaces(ipf, filters=filter_hostname, **api_options), fetch_device_vlans(ipf, filters=filter_hostname, **api_options), fetch_device_ipaddrs(ipf, filters=filter_hostname, **api_options), return_exceptions=True, ) async def gather_result(): res = await fut facts = res[0][0] return { "hostname": facts["hostname"], "facts": facts, "parts": res[1], "interfaces": res[2], "vlans": res[3], "ipaddrs": res[4], } return gather_result()
async def example(site, **options): async with IPFabricClient() as ipf: return await ipf.fetch_table( url="/tables/inventory/devices", filters=ipf.parse_filter(f"siteName = {site}"), columns=["hostname", "loginIp"], **options, )
async def demo(site) -> List[Dict]: async with IPFabricClient() as ipf: hosts = await fetch_site_devices(ipf, site) # create a coroutine for each of the device information fetches tasks = [device_info(ipf, host) for host in hosts] # run all device fetches concurrently and return the list of dicts return await asyncio.gather(*tasks)
async def run(ipf: IPFabricClient, device_list, callback): def _done(_task: asyncio.Task): _host = _task.get_name() _res = _task.result() if not len(_res): print(f"IPF device not found: {_host}") return callback(_host, _res[0]) tasks = {[ (task := loop.create_task( ipf.fetch_devices( filters=ipf.parse_filter(f"hostname ~ '{host}'")), name=host, )), task.add_done_callback(_done), ][0] for host in device_list}
async def fetch_site_devices(ipf: IPFabricClient, site: str) -> List: """ return a list of hostnames in the give site """ request = { TableFields.snapshot: ipf.active_snapshot, TableFields.columns: ["hostname"], TableFields.filters: ipf.parse_filter(f"siteName = {site}"), } res = await ipf.api.post(url=URIs.devices, json=request) res.raise_for_status() return [rec["hostname"] for rec in res.json()["data"]]
async def demo(hostname: str, show_config=False): async with IPFabricClient() as ipf: rec, config_text = await fetch_most_recent_config(ipf, hostname) change_dt = maya.MayaDT(rec["lastChange"] / 1000) check_dt = maya.MayaDT(rec["lastCheck"] / 1000) print("Last Changed:", change_dt.slang_date(), ",", change_dt.slang_time()) print("Last Checked", check_dt.slang_date(), ",", check_dt.slang_time()) if show_config: print(config_text) print(rec)
async def fetch_most_recent_config(ipf: IPFabricClient, hostname: str): """ Fetch the most recent configuration for the given device with `hostname`. Parameters ---------- ipf: IPFabricClient hostname: str The hostname of the device. Will match using the "like" operator to handle ignore-case. Returns ------- tuple [0]: dict - the config record that contains the lastChange and lastCheck IPF timestamps [1]: str - the configuration text """ # first we need to retrieve the most recent config record for this device. # The record contains information about the backup, which includes the # "hash" value that is required to actually retrieve the configuration text. res = await ipf.fetch_table( url=URIs.device_config_refs, columns=[ "sn", "hostname", "lastChange", "lastCheck", "status", "hash" ], pagination={"limit": 1}, sort={ "column": "lastCheck", "order": "desc" }, filters=ipf.parse_filter(f"hostname ~ {hostname}"), ) rec = res[0] # using the backup record hash value, retrieve the actual configuration # text. the call to API GET returns the context as text in the reposne body. res = await ipf.api.get(url=URIs.download_device_config, params=dict(hash=rec["hash"])) res.raise_for_status() return rec, res.text
name=host, )), task.add_done_callback(_done), ][0] for host in device_list} await asyncio.gather(*tasks) async def demo(filename): if not (fp := Path(filename)).is_file(): sys.exit(f"File does not exist: {filename}") device_list = fp.read_text().splitlines() fields = ("hostname", "family", "version", "model") get_fields = itemgetter(*fields) results = list() def callback(name, rec): print(f"Adding {name}") results.append(get_fields(rec)) async with IPFabricClient() as ipf: await run(ipf, device_list, callback=callback) print( tabulate(headers=fields, tabular_data=sorted(results, key=itemgetter(1, 2))))
async def example(**options): async with IPFabricClient() as ipf: res = await ipf.fetch_devices(**options) print(f"There are {len(res)} devices in IP Fabric")
import asyncio from aioipfabric import IPFabricClient ipf = IPFabricClient() async def demo(): tasks = list() for count in range(10): task = asyncio.create_task( ipf.fetch_table( url="/tables/inventory/interfaces", columns=["hostname", "intName", "siteName"], return_as="raw", )) tasks.append(task) return await asyncio.gather(*tasks, return_exceptions=True) async def demo2(url, columns, page_sz=500, timeout=60 * 5): res = await ipf.fetch_table(url=url, columns=columns, pagination=dict(start=0, limit=1), return_as="meta") count = res["count"] pages, more = divmod(count, page_sz) if more: pages += 1