Debian Codegraph @

examples/run_eos_commands.py

raw symbols SCIP
1 # Copyright (c) 2024 Arista Networks, Inc.
2 # Use of this source code is governed by the Apache License 2.0
3 # that can be found in the LICENSE file.
4 """Script that runs a list of EOS commands on reachable devices."""
5
6 from __future__ import annotations
7
8 import asyncio
9 from pprint import pprint
10
11 from anta.inventory import AntaInventory
12 from anta.models import AntaCommand
13
14
15 async def main(inv: AntaInventory, commands: list[str]) -> dict[str, list[AntaCommand]]:
16 """Run a list of commands against each valid device in the inventory.
17
18 Take an AntaInventory and a list of commands as string
19 1. try to connect to every device in the inventory
20 2. collect the results of the commands from each device
21
22 Returns
23 -------
24 dict[str, list[AntaCommand]]
25 a dictionary where key is the device name and the value is the list of AntaCommand ran towards the device
26 """
27 await inv.connect_inventory()
28
29 # Make a list of coroutine to run commands towards each connected device
30 coros = []
31 # dict to keep track of the commands per device
32 result_dict = {}
33 for name, device in inv.get_inventory(established_only=True).items():
34 anta_commands = [AntaCommand(command=command, ofmt="json") for command in commands]
35 result_dict[name] = anta_commands
36 coros.append(device.collect_commands(anta_commands))
37
38 # Run the coroutines
39 await asyncio.gather(*coros)
40
41 return result_dict
42
43
44 if __name__ == "__main__":
45 # Create the AntaInventory instance
46 inventory = AntaInventory.parse(
47 filename="inventory.yaml",
48 username="arista",
49 password="@rista123",
50 )
51
52 # Create a list of commands with json output
53 command_list = ["show version", "show ip bgp summary"]
54
55 # Run the main asyncio entry point
56 res = asyncio.run(main(inventory, command_list))
57
58 pprint(res)