Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"makefile.configureOnOpen": true
}
131 changes: 131 additions & 0 deletions examples/async_api_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
#!/usr/bin/env python
#
# Copyright (c) 2024, Arista Networks, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# Neither the name of Arista Networks nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARISTA NETWORKS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

"""
Example script for using the async API modules in pyeapi
"""

import asyncio
import sys
import pyeapi


async def get_vlans(node):
"""Get all VLANs from the device asynchronously"""
all_vlans = await node.api['vlansasync'].getall()
return all_vlans


async def create_vlan(node, vlan_id, vlan_name):
"""Create a new VLAN on the device asynchronously"""
vlans = node.api['vlansasync']

# Create the VLAN
result = await vlans.create(vlan_id)
if not result:
print(f"Failed to create VLAN {vlan_id}")
return False

# Set the VLAN name
result = await vlans.set_name(vlan_id, vlan_name)
if not result:
print(f"Failed to set name for VLAN {vlan_id}")
return False

return True


async def delete_vlan(node, vlan_id):
"""Delete a VLAN from the device asynchronously"""
result = await node.api['vlansasync'].delete(vlan_id)
return result


async def main():
"""Main function to demonstrate async API functionality"""
# Connect to the device
try:
# You can use connect_to_async to connect using a profile from eapi.conf
# node = await pyeapi.connect_to_async('veos01')

# Or connect directly with parameters
node = await pyeapi.connect_async(
transport='https',
host='localhost',
username='admin',
password='',
port=443,
return_node=True
)

# Load the API modules
node.api_autoload()

# Get all VLANs
print("Getting all VLANs...")
vlans = await get_vlans(node)
print(f"Current VLANs: {vlans}")

# Create a new VLAN
vlan_id = '100'
vlan_name = 'Test_VLAN_100'
print("Creating VLAN...")
result = await create_vlan(node, vlan_id, vlan_name)
if result:
print(f"Successfully created VLAN {vlan_id}")

# Get the VLANs again to see the new VLAN
print("Getting all VLANs after creation...")
vlans = await get_vlans(node)
print(f"Updated VLANs: {vlans}")

# Delete the VLAN
print(f"Deleting VLAN {vlan_id}...")
result = await delete_vlan(node, vlan_id)
if result:
print(f"Successfully deleted VLAN {vlan_id}")

# Get the VLANs again to confirm deletion
print("Getting all VLANs after deletion...")
vlans = await get_vlans(node)
print(f"Final VLANs: {vlans}")

except Exception as e:
print(f"Error: {e}")
return 1

return 0


if __name__ == '__main__':
sys.exit(asyncio.run(main()))
109 changes: 109 additions & 0 deletions examples/async_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
#!/usr/bin/env python
#
# Copyright (c) 2024, Arista Networks, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# Neither the name of Arista Networks nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARISTA NETWORKS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

"""
Example script for using the async functionality in pyeapi
"""

import asyncio
import pyeapi
import sys


async def get_version(node):
"""Get the version of the device asynchronously"""
version = await node.get_version()
return version


async def get_running_config(node):
"""Get the running config of the device asynchronously"""
config = await node.get_running_config()
return config


async def run_commands(node, commands):
"""Run commands on the device asynchronously"""
result = await node.enable(commands)
return result


async def main():
"""Main function to demonstrate async functionality"""
# Connect to the device
try:
# You can use connect_to_async to connect using a profile from eapi.conf
# node = await pyeapi.connect_to_async('veos01')

# Or connect directly with parameters
node = await pyeapi.connect_async(
transport='https',
host='localhost',
username='admin',
password='',
port=443,
return_node=True
)

# Run multiple commands concurrently
version_task = asyncio.create_task(get_version(node))
config_task = asyncio.create_task(get_running_config(node))
commands_task = asyncio.create_task(run_commands(node, ['show version', 'show interfaces']))

# Wait for all tasks to complete
version = await version_task
config = await config_task
commands_result = await commands_task

# Print results
print(f"Version: {version}")
print(f"Config length: {len(config)} characters")
print(f"Commands result: {commands_result}")

# Configure the device asynchronously
config_result = await node.config(['hostname async-test'])
print(f"Config result: {config_result}")

# Get a section of the config asynchronously
hostname_section = await node.section('hostname')
print(f"Hostname section: {hostname_section}")

except Exception as e:
print(f"Error: {e}")
return 1

return 0


if __name__ == '__main__':
sys.exit(asyncio.run(main()))
2 changes: 0 additions & 2 deletions examples/simple.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,3 @@
output = connection.execute(['enable', 'show version'])

print(('My system MAC address is', output['result'][1]['systemMacAddress']))


4 changes: 3 additions & 1 deletion pyeapi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,7 @@


from .client import load_config, connect, connect_to, config_for
from .clientasync import connect_async, connect_to_async

__all__ = ['load_config', 'connect', 'connect_to', 'config_for']
__all__ = ['load_config', 'connect', 'connect_to', 'config_for',
'connect_async', 'connect_to_async']
4 changes: 3 additions & 1 deletion pyeapi/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,7 @@
# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
from .abstract import Entity, EntityCollection
from .abstractasync import EntityAsync, EntityCollectionAsync

__all__ = ['Entity', 'EntityCollection']
__all__ = ['Entity', 'EntityCollection',
'EntityAsync', 'EntityCollectionAsync']
2 changes: 2 additions & 0 deletions pyeapi/api/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ class BaseEntity(object):
Args:
node (Node): An instance of Node
"""

def __init__(self, node):
self.node = node

Expand Down Expand Up @@ -188,6 +189,7 @@ class Entity(BaseEntity, Callable):

Examples of Entity candidates include global spanning tree
"""

def __call__(self):
return self.get()

Expand Down
Loading
Loading