### Initiate and Manage Config Sessions in Python Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/configsessions.md Demonstrates how to connect to a device, start a configuration session, view differences, and then either abort or commit the changes. ```python import pyeapi node = pyeapi.connect_to('veos01') vlans = node.api('vlans') node.configure_session() node.diff() # Sends "configure session 9c27d0e8-afef-4afd-95ae-3e3200bb7a3e" and "show session-config diff" node.abort() # Sends "configure session 9c27d0e8-afef-4afd-95ae-3e3200bb7a3e" and "abort" # or node.commit() # Sends "configure session 9c27d0e8-afef-4afd-95ae-3e3200bb7a3e" and "commit" ``` -------------------------------- ### Example eapi.conf Configuration File Source: https://context7.com/arista-eosplus/pyeapi/llms.txt This INI-style file centralizes node connection settings and is automatically searched by pyeapi. ```ini # ~/.eapi.conf [connection:veos01] host: 192.168.1.10 transport: https username: admin password: mysecret [connection:veos02] host: 192.168.1.11 transport: https_certs cert_file: /path/to/client.crt key_file: /path/to/client.key ca_file: /path/to/ca.crt [connection:veos03] transport: http username: admin password: admin tags: datacenter, spine [connection:localhost] transport: socket [DEFAULT] transport: https username: admin password: admin ``` -------------------------------- ### Install Pyeapi Development Requirements Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/install.md Install the necessary dependencies for Pyeapi development by running pip with the requirements file. ```console admin:~ admin$ pip install -r dev-requirements.txt ``` -------------------------------- ### Configure Pyeapi Installation on Reboot Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/install.md Add these commands to `/mnt/flash/rc.eos` to ensure Pyeapi is re-installed automatically after each reboot when installing offline. ```bash #!/bin/bash sudo pip install /mnt/flash/netaddr-.tar.gz sudo pip install /mnt/flash/pyeapi-.tar.gz ``` -------------------------------- ### Install Pyeapi from Source (Editable Mode) Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/install.md Install Pyeapi in editable mode using pip, which links the installed package to your local source code. This is useful for development. ```console admin:~ admin$ cd ~/projects/pyeapi # Install admin:~ admin$ sudo pip install -e ~/projects/pyeapi ``` -------------------------------- ### Install Pyeapi with Pip (Network Access) Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/install.md Use this command to install Pyeapi when your system has internet access. Pip will automatically handle dependencies like netaddr. ```console admin:~ admin$ sudo pip install pyeapi ``` -------------------------------- ### Update Pyeapi from Source Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/install.md If you installed Pyeapi from source using `pip install -e`, simply pull the latest changes from the Git repository to update your installation. ```shell admin:~ admin$ cd ~/projects/pyeapi admin:~ admin$ git pull ``` -------------------------------- ### Install Pyeapi Offline from Flash Storage Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/install.md Install Pyeapi and its dependency netaddr from the files transferred to the switch's flash storage. Replace with the actual package version. ```console [admin@veos ~]$ sudo pip install /mnt/flash/netaddr-.tar.gz [admin@veos ~]$ sudo pip install /mnt/flash/pyeapi-.tar.gz ``` -------------------------------- ### Upgrade Pyeapi with Pip Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/install.md Run this command to upgrade Pyeapi to the latest version if it's already installed. ```console admin:~ admin$ sudo pip install --upgrade pyeapi ``` -------------------------------- ### Node.get_config(config, as_string) Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Retrieves the device configuration, either `running-config` or `startup-config`, and returns it as a list of lines or a raw string. ```APIDOC ## Node.get_config(config, as_string) — Retrieve device configuration Fetches the `running-config` or `startup-config` from the device, returned as either a list of lines or a raw string. ```python import pyeapi node = pyeapi.connect_to('veos01') # As a string (default: running-config) running = node.get_config(as_string=True) print(running[:300]) # As a list of lines lines = node.get_config() vlan_lines = [l for l in lines if 'vlan' in l.lower()] # Startup config as string startup = node.get_config('startup-config', as_string=True) # With 'all' keyword to include defaults full = node.get_config(params='all', as_string=True) # Access via lazy-loaded properties print(node.running_config[:100]) print(node.startup_config[:100]) ``` ``` -------------------------------- ### Retrieve device configuration with Node.get_config() Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Use `node.get_config()` to fetch `running-config` or `startup-config`. Results can be returned as a list of lines or a raw string. Lazy-loaded properties like `node.running_config` are also available. ```python import pyeapi node = pyeapi.connect_to('veos01') # As a string (default: running-config) running = node.get_config(as_string=True) print(running[:300]) # As a list of lines lines = node.get_config() vlan_lines = [l for l in lines if 'vlan' in l.lower()] # Startup config as string startup = node.get_config('startup-config', as_string=True) # With 'all' keyword to include defaults full = node.get_config(params='all', as_string=True) # Access via lazy-loaded properties print(node.running_config[:100]) print(node.startup_config[:100]) ``` -------------------------------- ### Basic HTTP/HTTPS Connection Configuration Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/configfile.md Configure basic HTTP or HTTPS connections to a device. Ensure the configuration file is placed at `/mnt/flash/eapi.conf` for on-box connections. ```console [connection:localhost] transport: http[s] username: admin password: admin ``` -------------------------------- ### Connect and Run Commands with pyeapi Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/release-notes-0.6.0.md Demonstrates how to establish a connection to a device and execute single or multiple commands. Supports multiline commands without requiring a dictionary format. ```python >>> import pyeapi >>> connection = pyeapi.client.connect( ... transport='https', ... host='192.168.56.201', ... username='vagrant', ... password='vagrant', ... port=443, ... timeout=60 ... ) >>> device = pyeapi.client.Node(connection) >>> device.run_commands('show hostname') [{u'hostname': u'localhost', u'fqdn': u'localhost'}] >>> device.run_commands('show banner login') [{u'loginBanner': u''}] ``` ```python >>> my_commands = [ ... 'configure session whatever', ... 'hostname new-hostname', ... 'banner login MULTILINE:This is a new banner\nwith different lines!!!', ... 'end' ... ] >>> >>> device.run_commands(my_commands) [{}, {}, {}, {}] ``` ```python >>> print device.run_commands(['show session-config named whatever diffs'], encoding='text')[0]['output'] --- +++ system:/running-config @@ -3,6 +3,8 @@ ! boot system flash:/vEOS-lab.swi ! transceiver qsfp default-mode 4x10G +! hostname new-hostname ! spanning-tree mode mstp ! @@ -22,6 +24,11 @@ ! no ip routing ! +banner login +This is a new banner +with different lines!!! +EOF +! management api http-commands no shutdown ! ``` ```python >>> device.run_commands(['configure session whatever', 'commit']) [{}, {}] ``` ```python >>> device.run_commands('show hostname') [{u'hostname': u'new-hostname', u'fqdn': u'new-hostname'}] ``` ```python >>> device.run_commands('show banner login') [{u'loginBanner': u'This is a new banner\nwith different lines!!!\n'}] ``` -------------------------------- ### Subinterface Created Configuration Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/subinterfaces.md The configuration after successfully creating the subinterface. ```shell ! interface Ethernet1 no switchport ! interface Ethernet1.1 ! ``` -------------------------------- ### Off-box HTTP/HTTPS Connection Configuration Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/configfile.md Configure off-box connections using HTTP or HTTPS. Credentials are required for authentication. Place the configuration file in `$HOME/.eapi.conf`. ```console [connection:veos01] transport: http username: paul password: nottelling ``` ```console [connection:veos03] transport: https username: bob password: mysecret ``` ```console [connection:veos04] host: 192.168.2.10 transport: https username: admin password: admin ``` -------------------------------- ### Handle Invalid Configuration within a Session Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/configsessions.md Shows how to use configuration sessions with multiple interface configuration commands and how to abort the entire session if any command fails. ```python node = pyeapi.connect_to('veos01') interfaces = node.api('interfaces') node.configure_session() if not (interfaces.configure(['interface Eth6', 'no switchport', 'ip address 172.16.0.1/30']) and \ interfaces.configure(['interface Eth7', 'no switchport', 'ip address 172.16.0.1/30'])): node.abort() # This aborts everything!! ``` -------------------------------- ### Transfer Pyeapi Packages to Switch Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/install.md Use SCP to copy the Pyeapi and netaddr package files to the Arista switch's flash storage when installing without network access. ```console admin:~ admin$ scp path/to/pyeapi-.tar.gz ansible@veos01:/mnt/flash/ admin:~ admin$ scp path/to/netaddr-.tar.gz ansible@veos01:/mnt/flash/ ``` -------------------------------- ### Primary Interface Configuration Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/subinterfaces.md This is the expected running configuration after creating the primary interface in routed mode. ```shell ! interface Ethernet1 no switchport ! ``` -------------------------------- ### Create Node from eapi.conf using pyeapi.connect_to() Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Looks up a connection profile by name in the loaded eapi.conf and returns an initialized Node instance. Raises AttributeError if the profile is not found or ConnectionError if connection fails. ```python import pyeapi from pyeapi.eapilib import CommandError, ConnectionError pyeapi.load_config('/etc/myapp/eapi.conf') try: node = pyeapi.connect_to('veos01') print(repr(node)) # Node(connection=https://192.168.1.10:443/command-api) except AttributeError as e: print('Profile not found:', e) except ConnectionError as e: print('Could not connect:', e) ``` -------------------------------- ### Run enable-mode commands with Node.enable() Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Use `node.enable()` to send show/exec commands. It supports single or multiple commands, JSON or text encoding, and strict mode for error handling. Falls back to text encoding if JSON is not supported. ```python import pyeapi node = pyeapi.connect_to('veos01') # Single command result = node.enable('show version') print(result[0]['result']['version']) # '4.28.0F' print(result[0]['result']['modelName']) # 'DCS-7050CX3-32S' # Multiple commands results = node.enable(['show hostname', 'show ip interface brief']) for r in results: print(r['command'], '->', r['encoding']) # Force text encoding result = node.enable('show running-config', encoding='text') print(result[0]['result']['output'][:200]) # Versioned command (request specific API revision) result = node.enable({'cmd': 'show cvx', 'revision': 2}) print(result[0]['result']) # Strict mode: raise immediately on any failure instead of retrying with text try: result = node.enable(['show version', 'show nonexistent'], strict=True) except Exception as e: print('Command failed:', e) ``` -------------------------------- ### Using DEFAULT Section for Global Settings Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/configfile.md Utilize the `[DEFAULT]` section to define global settings such as transport, username, and password that apply to all connections unless overridden by specific connection configurations. ```console [connection:veos01] [connection:veos03] transport: https username: bob password: mysecret [connection:veos04] host: 192.168.2.10 [DEFAULT] transport: https username: admin password: admin ``` -------------------------------- ### HTTPS with Certificates Configuration Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/configfile.md Configure HTTPS connections using client certificates for authentication. Ensure certificates are properly set up and trusted by EOS. The `ca_file` parameter is optional for validating the switch's certificate. ```console [connection:veos01] transport: https_certs cert_file: /path/to/certificate/file key_file: /path/to/private/key/file ca_file: /path/to/CA/certificate/file ``` ```console [connection:veos02] transport: https_certs cert_file: /path/to/certificate/file key_file: /path/to/private/key/file ``` -------------------------------- ### Connect to a Node and Execute Commands Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/quickstart.md Instantiate a Node object to connect to an EOS device and execute commands. Supports single commands, commands with specific revisions, configuration changes, and multiple commands. ```python # start by importing the library import pyeapi # create a node object by specifying the node to work with node = pyeapi.connect_to('veos01') ``` ```python # send one or more commands to the node node.enable('show hostname') [{'command': 'show hostname', 'encoding': 'json', 'result': {u'hostname': u'veos01', u'fqdn': u'veos01.arista.com'}}] ``` ```python # Request a specific revision of a command that has been updated node.enable({'cmd': 'show cvx', 'revision': 2}) [{'command': {'cmd': 'show cvx', 'revision': 2}, 'encoding': 'json', 'result': {u'clusterMode': False, u'controllerUUID': u'', u'enabled': False, u'heartbeatInterval': 20.0, u'heartbeatTimeout': 60.0}}] ``` ```python # use the config method to send configuration commands node.config('hostname veos01') [{}] ``` ```python # multiple commands can be sent by using a list # (works for both enable or config) node.config(['interface Ethernet1', 'description foo']) [{}, {}] ``` ```python # return the running or startup configuration from the # node (output omitted for brevity) node.running_config ``` ```python node.startup_config ``` -------------------------------- ### Load Custom eapi.conf and Connect to Node Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Loads a custom eapi.conf file from a specified path and establishes a connection to a node defined within it. Requires the pyeapi library to be imported. ```python import pyeapi # Load a project-specific config instead of ~/.eapi.conf pyeapi.load_config('/etc/myapp/eapi.conf') node = pyeapi.connect_to('veos01') print(node.enable('show hostname')) # [{'command': 'show hostname', 'encoding': 'json', # 'result': {'hostname': 'veos01', 'fqdn': 'veos01.example.com'}}] ``` -------------------------------- ### Configure System Settings with pyeapi Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Manage global EOS system settings like hostname, IP routing, and banners. Use `default=True` to reset a setting. ```python import pyeapi node = pyeapi.connect_to('veos01') system = node.api('system') config = system.get() print(config) ``` ```python system.set_hostname('spine-01') system.set_iprouting(True) system.set_iprouting(False) system.set_banner('login', 'Authorized access only.\nAll activity is monitored.') system.set_banner('motd', 'Welcome to spine-01.') system.set_hostname(default=True) ``` -------------------------------- ### Node.config(commands) Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Wraps commands with `configure terminal`, sends them to the node, and returns the response list. It automatically refreshes `running_config` if `autorefresh=True`. ```APIDOC ## Node.config(commands) — Send configuration commands Wraps commands with `configure terminal`, sends them to the node, and returns the response list. Automatically refreshes `running_config` if `autorefresh=True`. ```python import pyeapi node = pyeapi.connect_to('veos01') # Single command node.config('hostname spine-01') # Multiple commands as a list node.config([ 'interface Ethernet1', 'description uplink-to-core', 'no shutdown' ]) # Disable autorefresh for bulk changes, refresh manually at the end node.autorefresh = False for vlan_id in range(100, 110): node.config('vlan %d' % vlan_id) node.refresh() # manually reload running_config # CliVariants: try newer EOS syntax first, fall back to older form from pyeapi.utils import CliVariants node.config([ 'interface Vxlan1', CliVariants('vxlan multicast-group decap', 'vxlan multicast-group') ]) ``` ``` -------------------------------- ### Configure Sessions with Node.configure_session(), Node.commit(), Node.abort() Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Leverages EOS configuration sessions to stage changes and commit (or abort) them atomically. Use this for transactional configuration changes. ```python import pyeapi from pyeapi.eapilib import CommandError node = pyeapi.connect_to('veos01') # Enter a named config session node.configure_session() # Stage configuration changes inside the session node.config([ 'interface Ethernet1', 'description new-uplink', 'ip address 10.1.1.1/30' ]) # Preview diffs before committing print(node.diff()) # --- system:/running-config # +++ session:/session-abc123/config # @@ ... @@ # + description new-uplink # + ip address 10.1.1.1/30 try: node.commit() # atomically apply the staged changes print('Committed successfully') except CommandError as e: node.abort() # roll back all staged changes print('Commit failed, aborted:', e) ``` -------------------------------- ### Create Direct Connection with pyeapi.connect() Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Establishes a direct connection to a network device using provided parameters, bypassing the need for an eapi.conf file. Can return either a raw connection object or a Node object. ```python import pyeapi import ssl # Basic HTTPS connection returning a Node node = pyeapi.connect( host='192.168.1.10', transport='https', username='admin', password='secret', return_node=True ) # HTTPS with custom SSL context (e.g. to handle older EOS cipher suites) ctx = ssl.create_default_context() ctx.set_ciphers('DEFAULT') ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE node = pyeapi.connect(host='192.168.1.10', transport='https', username='admin', password='secret', context=ctx, return_node=True) # Raw connection object (low-level execute) conn = pyeapi.connect(host='192.168.1.10', transport='http', username='admin', password='secret') response = conn.execute(['show version']) print(response['result'][0]['version']) # e.g. '4.28.0F' ``` -------------------------------- ### Send configuration commands with Node.config() Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Use `node.config()` to send configuration commands. It wraps commands with `configure terminal` and returns a response list. Autorefresh can be enabled or disabled for manual refresh. ```python import pyeapi node = pyeapi.connect_to('veos01') # Single command node.config('hostname spine-01') # Multiple commands as a list node.config([ 'interface Ethernet1', 'description uplink-to-core', 'no shutdown' ]) # Disable autorefresh for bulk changes, refresh manually at the end node.autorefresh = False for vlan_id in range(100, 110): node.config('vlan %d' % vlan_id) node.refresh() # manually reload running_config # CliVariants: try newer EOS syntax first, fall back to older form from pyeapi.utils import CliVariants node.config([ 'interface Vxlan1', CliVariants('vxlan multicast-group decap', 'vxlan multicast-group') ]) ``` -------------------------------- ### Node.enable(commands) Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Sends one or more show/exec commands to the node in enable mode. It returns a list of result dictionaries and automatically falls back to text encoding when a command does not support JSON. ```APIDOC ## Node.enable(commands) — Run enable-mode commands Sends one or more show/exec commands to the node in enable mode. Returns a list of result dicts. Falls back to text encoding automatically when a command does not support JSON. ```python import pyeapi node = pyeapi.connect_to('veos01') # Single command result = node.enable('show version') print(result[0]['result']['version']) # '4.28.0F' print(result[0]['result']['modelName']) # 'DCS-7050CX3-32S' # Multiple commands results = node.enable(['show hostname', 'show ip interface brief']) for r in results: print(r['command'], '->', r['encoding']) # Force text encoding result = node.enable('show running-config', encoding='text') print(result[0]['result']['output'][:200]) # Versioned command (request specific API revision) result = node.enable({'cmd': 'show cvx', 'revision': 2}) print(result[0]['result']) # Strict mode: raise immediately on any failure instead of retrying with text try: result = node.enable(['show version', 'show nonexistent'], strict=True) except Exception as e: print('Command failed:', e) ``` ``` -------------------------------- ### Create Subinterface Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/subinterfaces.md This snippet demonstrates how to create a subinterface, such as Ethernet1.1, using the pyeapi interfaces API. ```python node.api('interfaces').create('Ethernet1.1') ``` -------------------------------- ### Extract a config section with Node.section() Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Use `node.section()` with a regex to extract a configuration block from running or startup config. Useful for isolating specific parts of the configuration. ```python import pyeapi node = pyeapi.connect_to('veos01') # Extract BGP config block bgp_section = node.section('router bgp') print(bgp_section) # router bgp 65001 # router-id 10.0.0.1 # neighbor 10.0.0.2 remote-as 65002 # ... # Extract a specific interface block eth1_section = node.section('interface Ethernet1') # From startup config startup_bgp = node.section('router bgp', config='startup_config') ``` -------------------------------- ### Node.section(regex) Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Extracts a configuration block from the running or startup config using a regex pattern to match the section header. ```APIDOC ## Node.section(regex) — Extract a config section Extracts a config block from the running or startup config using a regex pattern to match the section header. ```python import pyeapi node = pyeapi.connect_to('veos01') # Extract BGP config block bgp_section = node.section('router bgp') print(bgp_section) # router bgp 65001 # router-id 10.0.0.1 # neighbor 10.0.0.2 remote-as 65002 # ... # Extract a specific interface block eth1_section = node.section('interface Ethernet1') # From startup config startup_bgp = node.section('router bgp', config='startup_config') ``` ``` -------------------------------- ### pyeapi.connect_to(name) Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Looks up a connection profile by name in the loaded eapi.conf file and returns a fully initialized Node instance. This is a convenient way to establish a connection using pre-configured settings. ```APIDOC ## pyeapi.connect_to(name) ### Description Looks up `name` in the loaded `eapi.conf` and returns a fully initialized `Node` instance, raising `AttributeError` if the profile is not found. ### Parameters #### Path Parameters - **name** (string) - Required - The name of the connection profile to use from `eapi.conf`. ### Request Example ```python import pyeapi from pyeapi.eapilib import CommandError, ConnectionError pyeapi.load_config('/etc/myapp/eapi.conf') try: node = pyeapi.connect_to('veos01') print(repr(node)) # Node(connection=https://192.168.1.10:443/command-api) except AttributeError as e: print('Profile not found:', e) except ConnectionError as e: print('Could not connect:', e) ``` ### Response - **Node** - A `Node` object representing the connection to the device. ``` -------------------------------- ### System API Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Manages global EOS system settings including hostname, IP routing, and banners. ```APIDOC ## System API (`node.api('system')`) Manages global EOS system settings including hostname, IP routing, and banners. ### Methods - `system.get()`: Retrieves the current system configuration. - `system.set_hostname(hostname)`: Configures the system hostname. - `system.set_iprouting(enable)`: Enables or disables IP routing. - `system.set_banner(banner_type, text)`: Sets the login or MOTD banner. - `system.set_hostname(default=True)`: Resets the hostname to its default value. ``` -------------------------------- ### Low-level command execution with Node.run_commands() Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Use `node.run_commands()` for direct command execution without enable/config mode wrapping. Useful for raw JSON-RPC control, text encoding, and multiline commands. ```python import pyeapi node = pyeapi.connect_to('veos01') # Text encoding result = node.run_commands(['show running-config'], encoding='text') print(result[0]['output'][:100]) # JSON with expandAliases result = node.run_commands( ['enable', 'show interfaces'], send_enable=False, expandAliases=True ) # Multiline commands (banner config) node.run_commands([ 'enable', 'configure terminal', 'banner login MULTILINE: Welcome to veos01.\nUnauthorized access prohibited.\nEOF' ]) ``` -------------------------------- ### Manage BGP Configuration with pyeapi Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Configure global BGP settings and neighbors. Ensure BGP is enabled using `set_shutdown(disable=True)`. ```python import pyeapi node = pyeapi.connect_to('veos01') bgp = node.api('bgp') config = bgp.get() print(config) ``` ```python bgp.create(65001) bgp.set_router_id(65001, '10.0.0.1') bgp.set_maximum_paths(65001, 8, max_ecmp_paths=8) bgp.set_shutdown(65001, disable=True) # no shutdown (enable BGP) bgp.add_network(65001, '10.1.0.0', 24) bgp.remove_network(65001, '10.1.0.0', 24) ``` ```python neighbors = bgp.neighbors all_neighbors = neighbors.getall() neighbors.create('10.0.0.2') neighbors.set_remote_as('10.0.0.2', '65002') neighbors.set_description('10.0.0.2', 'spine-02') neighbors.set_next_hop_self('10.0.0.2', True) neighbors.set_send_community('10.0.0.2', True) neighbors.set_route_map_in('10.0.0.2', 'RM-IN') neighbors.set_route_map_out('10.0.0.2', 'RM-OUT') neighbors.set_shutdown('10.0.0.2', disable=True) # activate neighbor neighbors.delete('10.0.0.2') bgp.delete(65001) ``` -------------------------------- ### Retrieve Connection Settings from eapi.conf Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Retrieves the connection parameters dictionary for a named entry in the loaded eapi.conf file. Returns None if the profile is not found. ```python import pyeapi pyeapi.load_config('/etc/myapp/eapi.conf') settings = pyeapi.config_for('veos01') # {'host': '192.168.1.10', 'transport': 'https', # 'username': 'admin', 'password': 'mysecret'} if settings is None: print('Connection profile not found') else: print('Connecting to', settings.get('host')) ``` -------------------------------- ### Clone Pyeapi Repository Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/install.md Clone the Pyeapi GitHub repository to your local machine to set up for development. Navigate into the cloned directory afterwards. ```shell admin:~ admin$ cd ~/projects admin:~ admin$ git clone https://github.com/arista-eosplus/pyeapi.git admin:~ admin$ cd pyeapi ``` -------------------------------- ### Query Nodes by Tag Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Returns a list of connection names (hostnames) that share a specified tag, as defined in the eapi.conf file. Requires pyeapi to be imported and configuration to be loaded. ```python import pyeapi pyeapi.load_config('/etc/myapp/eapi.conf') # eapi.conf has: tags: datacenter, spine on veos03 spines = pyeapi.hosts_for_tag('spine') ``` -------------------------------- ### pyeapi.load_config(filename) Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Loads an eapi.conf file from a custom path into the global config instance, replacing the auto-discovered config. This allows for centralized management of connection settings. ```APIDOC ## pyeapi.load_config(filename) ### Description Loads an eapi.conf file from a custom path into the global config instance, replacing the auto-discovered config. ### Parameters #### Path Parameters - **filename** (string) - Required - The path to the eapi.conf file to load. ### Request Example ```python import pyeapi # Load a project-specific config instead of ~/.eapi.conf pyeapi.load_config('/etc/myapp/eapi.conf') node = pyeapi.connect_to('veos01') print(node.enable('show hostname')) ``` ### Response This function does not return a value directly but modifies the global configuration instance. ``` -------------------------------- ### Node.configure_session() / Node.commit() / Node.abort() Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Leverages EOS configuration sessions to stage changes and commit (or abort) them atomically. This allows for transactional configuration changes on network devices. ```APIDOC ## `Node.configure_session()` / `Node.commit()` / `Node.abort()` — Config sessions Leverages EOS configuration sessions to stage changes and commit (or abort) them atomically. ```python import pyeapi from pyeapi.eapilib import CommandError node = pyeapi.connect_to('veos01') # Enter a named config session node.configure_session() # Stage configuration changes inside the session node.config([ 'interface Ethernet1', 'description new-uplink', 'ip address 10.1.1.1/30' ]) # Preview diffs before committing print(node.diff()) # --- # system:/running-config # +++ session:/session-abc123/config # @@ ... @@ # + description new-uplink # + ip address 10.1.1.1/30 try: node.commit() # atomically apply the staged changes print('Committed successfully') except CommandError as e: node.abort() # roll back all staged changes print('Commit failed, aborted:', e) ``` ``` -------------------------------- ### Access Node Properties: version, version_number, model Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Lazily loaded properties that cache device identity information from 'show version'. Useful for version-aware configuration logic. ```python import pyeapi node = pyeapi.connect_to('veos01') print(node.version) # '4.28.0F' print(node.version_number) # '4.28' (numeric portion only) print(node.model) # '7050' (4-digit model number) # Version-aware configuration interfaces = node.api('interfaces') if node.version_number >= '4.23': # uses 'vrf ' syntax interfaces.set_vrf('Ethernet1', 'MGMT') else: # uses legacy 'vrf forwarding ' syntax pass ``` -------------------------------- ### pyeapi.connect() Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Creates a direct connection to an Arista EOS device using supplied parameters, bypassing the need for an eapi.conf file. It can return either a raw connection object or a Node object. ```APIDOC ## pyeapi.connect() ### Description Creates a connection directly using supplied parameters without requiring an `eapi.conf` file. Returns an `EapiConnection` by default, or a `Node` object when `return_node=True`. ### Parameters #### Query Parameters - **host** (string) - Required - The hostname or IP address of the Arista EOS device. - **transport** (string) - Required - The transport protocol to use (e.g., 'http', 'https', 'https_certs', 'socket'). - **username** (string) - Optional - The username for authentication. - **password** (string) - Optional - The password for authentication. - **context** (ssl.SSLContext) - Optional - A custom SSL context for HTTPS connections. - **return_node** (boolean) - Optional - If True, returns a `Node` object; otherwise, returns an `EapiConnection` object. Defaults to False. ### Request Example ```python import pyeapi import ssl # Basic HTTPS connection returning a Node node = pyeapi.connect( host='192.168.1.10', transport='https', username='admin', password='secret', return_node=True ) # HTTPS with custom SSL context ctx = ssl.create_default_context() ctx.set_ciphers('DEFAULT') ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE node = pyeapi.connect(host='192.168.1.10', transport='https', username='admin', password='secret', context=ctx, return_node=True) # Raw connection object (low-level execute) conn = pyeapi.connect(host='192.168.1.10', transport='http', username='admin', password='secret') response = conn.execute(['show version']) print(response['result'][0]['version']) ``` ### Response - **Node or EapiConnection** - An object representing the connection to the device. The type depends on the `return_node` parameter. ``` -------------------------------- ### Create Primary Interface for Subinterface Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/subinterfaces.md Before creating a subinterface, ensure the primary interface is configured in routed mode. This snippet connects to the switch and creates the primary interface. ```python import pyeapi node = pyeapi.connect_to('veos01') node.api('ipinterfaces').create('Ethernet1') ``` -------------------------------- ### Subinterface with Encapsulation Configuration Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/subinterfaces.md The running configuration reflecting the subinterface with its assigned VLAN encapsulation. ```shell ! interface Ethernet1 no switchport ! interface Ethernet1.1 encapsulation dot1q vlan 4 ! ``` -------------------------------- ### Configure Switchports with pyeapi Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Manage switchport modes, VLANs, and trunk groups. Use `delete` to remove a switchport configuration. ```python switchports.create('Ethernet2') switchports.set_mode('Ethernet2', 'trunk') switchports.set_trunk_native_vlan('Ethernet2', '100') switchports.set_trunk_allowed_vlans('Ethernet2', '100-200') switchports.add_trunk_group('Ethernet2', 'mlag') switchports.remove_trunk_group('Ethernet2', 'mlag') switchports.set_mode('Ethernet3', 'access') switchports.set_access_vlan('Ethernet3', '50') switchports.delete('Ethernet2') ``` ```python all_sp = switchports.getall() for name, attrs in all_sp.items(): print(f"{name}: mode={attrs['mode']}") ``` -------------------------------- ### Node.api(name) Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Dynamically loads a structured API module by name from the `pyeapi.api` namespace (or a custom namespace), returning an object bound to the current Node. ```APIDOC ## Node.api(name) — Autoload an API module Dynamically loads a structured API module by name from the `pyeapi.api` namespace (or a custom namespace), returning an object bound to the current Node. ```python import pyeapi node = pyeapi.connect_to('veos01') # Built-in modules: vlans, interfaces, switchports, bgp, system, # ipinterfaces, mlag, ntp, ospf, users, varp, vrfs, vrrp, # routemaps, staticroute, stp, acl vlans = node.api('vlans') system = node.api('system') bgp = node.api('bgp') # Custom namespace module custom = node.api('mymodule', namespace='mycompany.eos.api') ``` ``` -------------------------------- ### Autoload an API module with Node.api() Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Use `node.api()` to dynamically load structured API modules by name from `pyeapi.api` or a custom namespace. Returns an object bound to the current Node. ```python import pyeapi node = pyeapi.connect_to('veos01') # Built-in modules: vlans, interfaces, switchports, bgp, system, # ipinterfaces, mlag, ntp, ospf, users, varp, vrfs, vrrp, # routemaps, staticroute, stp, acl vlans = node.api('vlans') system = node.api('system') bgp = node.api('bgp') # Custom namespace module custom = node.api('mymodule', namespace='mycompany.eos.api') ``` -------------------------------- ### Switch Configuration for HTTP Local Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/configfile.md This is the required switch configuration to enable the HTTP local transport protocol, which must accompany the eapi.conf file when using http_local transport. ```text switch(config)#management http-server switch(config-mgmt-http-server)#protocol http localhost ``` -------------------------------- ### Node.run_commands(commands) Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Sends commands directly over the transport without any enable/config mode wrapping. Use this method when you need raw control over the JSON-RPC call. ```APIDOC ## Node.run_commands(commands) — Low-level command execution Sends commands directly over the transport without any enable/config mode wrapping. Use when you need raw control over the JSON-RPC call. ```python import pyeapi node = pyeapi.connect_to('veos01') # Text encoding result = node.run_commands(['show running-config'], encoding='text') print(result[0]['output'][:100]) # JSON with expandAliases result = node.run_commands( ['enable', 'show interfaces'], send_enable=False, expandAliases=True ) # Multiline commands (banner config) node.run_commands([ 'enable', 'configure terminal', 'banner login MULTILINE: Welcome to veos01.\nUnauthorized access prohibited.\nEOF' ]) ``` ``` -------------------------------- ### Work with Resource APIs (VLANs) Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/quickstart.md Access and manipulate specific EOS resources like VLANs using the pyeapi resource API. This includes retrieving all VLANs, a specific VLAN, creating a new VLAN, and setting its name. ```python # create a connection to the node import pyeapi node = pyeapi.connect_to('veos01') ``` ```python # get the instance of the API (in this case vlans) vlans = node.api('vlans') ``` ```python # return all vlans from the node vlans.getall() {'1': {'state': 'active', 'name': 'default', 'vlan_id': 1, 'trunk_groups': []}, '10': {'state': 'active', 'name': 'VLAN0010', 'vlan_id': 10, 'trunk_groups': []}} ``` ```python # return a specific vlan from the node vlans.get(1) {'state': 'active', 'name': 'default', 'vlan_id': 1, 'trunk_groups': []} ``` ```python # add a new vlan to the node vlans.create(100) True ``` ```python # set the new vlan name vlans.set_name(100, 'foo') True ``` -------------------------------- ### pyeapi.hosts_for_tag(tag) Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Returns a list of connection names that share a given tag defined in the eapi.conf file. This is useful for managing and connecting to groups of devices. ```APIDOC ## pyeapi.hosts_for_tag(tag) ### Description Returns a list of connection names that share a given tag defined in `eapi.conf`. ### Parameters #### Path Parameters - **tag** (string) - Required - The tag to filter connection names by. ### Request Example ```python import pyeapi pyeapi.load_config('/etc/myapp/eapi.conf') # eapi.conf has: tags: datacenter, spine on veos03 spines = pyeapi.hosts_for_tag('spine') ``` ### Response - **list** - A list of strings, where each string is a connection name matching the provided tag. ``` -------------------------------- ### Node.version / Node.version_number / Node.model Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Lazily loaded properties that cache device identity information from `show version`. These properties provide quick access to the device's software version and hardware model. ```APIDOC ## `Node.version` / `Node.version_number` / `Node.model` — Node properties Lazily loaded properties that cache device identity information from `show version`. ```python import pyeapi node = pyeapi.connect_to('veos01') print(node.version) # '4.28.0F' print(node.version_number) # '4.28' (numeric portion only) print(node.model) # '7050' (4-digit model number) # Version-aware configuration interfaces = node.api('interfaces') if node.version_number >= '4.23': # uses 'vrf ' syntax interfaces.set_vrf('Ethernet1', 'MGMT') else: # uses legacy 'vrf forwarding ' syntax pass ``` ``` -------------------------------- ### Set Subinterface VLAN Encapsulation Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/subinterfaces.md To apply a VLAN to a subinterface, use the set_encapsulation method with the subinterface name and VLAN ID. ```python node.api('interfaces').set_encapsulation('Ethernet1.1', 4) ``` -------------------------------- ### Checkout Pyeapi Version/Branch Source: https://github.com/arista-eosplus/pyeapi/blob/develop/docs/install.md Switch to a specific version or branch of the Pyeapi code using Git commands. Use `git tag` and `git branch` to see available options. ```shell admin:~ admin$ cd ~/projects/pyeapi # To see a list of available versions or branches admin:~ admin$ git tag admin:~ admin$ git branch # Checkout the desired version of code admin:~ admin$ git checkout v0.3.3 ``` -------------------------------- ### Interfaces API: Manage Ethernet, Port-Channel, VXLAN Source: https://context7.com/arista-eosplus/pyeapi/llms.txt Manages EOS interfaces including Ethernet, Port-Channel, and VXLAN types. Use for configuring interface attributes and settings. ```python import pyeapi node = pyeapi.connect_to('veos01') interfaces = node.api('interfaces') # Get interface details eth1 = interfaces.get('Ethernet1') print(eth1) # {'name': 'Ethernet1', 'type': 'ethernet', 'shutdown': False, # 'description': None, 'sflow': True, # 'flowcontrol_send': 'off', 'flowcontrol_receive': 'off'} # Get all interfaces all_intf = interfaces.getall() # Configure Ethernet interface interfaces.set_description('Ethernet1', 'uplink-to-spine-01') interfaces.set_shutdown('Ethernet1', disable=True) # no shutdown interfaces.set_shutdown('Ethernet3', disable=False) # shutdown interfaces.set_sflow('Ethernet1', disable=True) # no sflow interfaces.set_flowcontrol_send('Ethernet1', value='on') interfaces.set_vrf('Ethernet2', 'MGMT') # Ethernet subinterface interfaces.create('Ethernet1.10') interfaces.set_encapsulation('Ethernet1.10', vid=10) interfaces.delete('Ethernet1.10') # Port-Channel interface pc1 = interfaces.get('Port-Channel1') print(pc1['members']) # ['Ethernet1', 'Ethernet2'] print(pc1['lacp_mode']) # 'active' interfaces.set_members('Port-Channel1', ['Ethernet1', 'Ethernet2'], mode='active') interfaces.set_minimum_links('Port-Channel1', value=1) interfaces.set_lacp_fallback('Port-Channel1', mode='individual') interfaces.set_lacp_timeout('Port-Channel1', value=30) # VXLAN interface vxlan = interfaces.get('Vxlan1') print(vxlan['source_interface']) # 'Loopback0' print(vxlan['vlans']) # {'100': {'vni': '10100', 'flood_list': []}} interfaces.set_source_interface('Vxlan1', value='Loopback0') interfaces.set_udp_port('Vxlan1', value=4789) interfaces.update_vlan('Vxlan1', vid=100, vni=10100) interfaces.add_vtep('Vxlan1', '10.0.0.2') interfaces.add_vtep('Vxlan1', '10.0.0.3', vlan=100) # per-VLAN flood list interfaces.remove_vtep('Vxlan1', '10.0.0.3', vlan=100) interfaces.remove_vlan('Vxlan1', vid=100) ```