CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-junos-eznc

Junos 'EZ' automation library for remotely managing and automating Juniper Networks Junos devices through NETCONF protocol

Pending
Overview
Eval results
Files

exceptions.mddocs/

Exception Handling

Comprehensive exception hierarchy for handling all types of errors including connection failures, RPC errors, configuration problems, operational issues, and data processing errors. Provides structured error handling with detailed error information and recovery guidance.

Capabilities

Base Exception Classes

Foundation exception classes that provide the basis for all junos-eznc specific exceptions.

class RpcError(Exception):
    """
    Base class for RPC-related exceptions.
    
    Attributes:
    - message (str): Error message
    - rpc_error (dict): Detailed RPC error information
    - cmd (str): RPC command that failed
    - rsp (Element): RPC response XML element
    """
    
    def __init__(self, cmd=None, rsp=None, errs=None, dev=None, timeout=None, re=None):
        """
        Initialize RPC error.
        
        Parameters:
        - cmd: RPC command that failed
        - rsp: RPC response element
        - errs: Error list
        - dev: Device object
        - timeout: RPC timeout value
        - re: Routing engine identifier
        """

class ConnectError(Exception):
    """
    Base class for connection-related exceptions.
    
    Attributes:
    - dev (Device): Device object that failed to connect
    - msg (str): Error message
    """
    
    def __init__(self, dev, msg=None):
        """
        Initialize connection error.
        
        Parameters:
        - dev (Device): Device object
        - msg (str): Error message
        """

class FactLoopError(Exception):
    """
    Exception for fact gathering infinite loops.
    
    Raised when fact gathering encounters circular dependencies
    or infinite loops during device fact collection.
    """

RPC Exception Classes

Specific exceptions for RPC operation failures including configuration errors, timeout issues, and operational problems.

class CommitError(RpcError):
    """
    Configuration commit operation errors.
    
    Raised when configuration commit operations fail due to
    validation errors, conflicts, or system issues.
    """

class ConfigLoadError(RpcError):
    """
    Configuration load operation errors.
    
    Raised when loading configuration data fails due to
    syntax errors, invalid configurations, or load conflicts.
    """

class LockError(RpcError):
    """
    Configuration lock operation errors.
    
    Raised when attempting to lock configuration database
    that is already locked by another user or session.
    """

class UnlockError(RpcError):
    """
    Configuration unlock operation errors.
    
    Raised when attempting to unlock configuration database
    fails or when database is not locked.
    """

class PermissionError(RpcError):
    """
    Permission denied errors.
    
    Raised when user lacks sufficient privileges to perform
    the requested operation.
    """

class RpcTimeoutError(RpcError):
    """
    RPC operation timeout errors.
    
    Raised when RPC operations exceed configured timeout
    values during execution.
    """

class SwRollbackError(RpcError):
    """
    Software rollback operation errors.
    
    Raised when software installation fails and automatic
    rollback operations encounter problems.
    """

Connection Exception Classes

Specific exceptions for connection establishment and management failures.

class ProbeError(ConnectError):
    """
    Device probe operation failures.
    
    Raised when device connectivity probing fails to
    reach the target device.
    """

class ConnectAuthError(ConnectError):
    """
    Authentication failures during connection.
    
    Raised when authentication fails due to invalid
    credentials or authentication method issues.
    """

class ConnectTimeoutError(ConnectError):
    """
    Connection timeout errors.
    
    Raised when connection establishment exceeds the
    configured timeout period.
    """

class ConnectUnknownHostError(ConnectError):
    """
    Unknown host resolution errors.
    
    Raised when hostname resolution fails or the
    target host cannot be found.
    """

class ConnectRefusedError(ConnectError):
    """
    Connection refused by target.
    
    Raised when the target device actively refuses
    the connection attempt.
    """

class ConnectNotMasterError(ConnectError):
    """
    Connection not to master routing engine.
    
    Raised when connection is established to backup
    routing engine but master was expected.
    """

class ConnectClosedError(ConnectError):
    """
    Unexpected connection closure.
    
    Raised when connection is unexpectedly closed
    during operation.
    """

Data Processing Exception Classes

Exceptions for data parsing, processing, and format conversion errors.

class JSONLoadError(Exception):
    """
    JSON parsing and loading errors.
    
    Raised when JSON data parsing fails due to invalid
    JSON format or structure issues.
    
    Attributes:
    - data (str): JSON data that failed to parse
    - message (str): Error message
    """
    
    def __init__(self, data, message):
        """
        Initialize JSON load error.
        
        Parameters:
        - data (str): JSON data that failed
        - message (str): Error description
        """

Usage Examples

Basic Exception Handling

from jnpr.junos import Device
from jnpr.junos.exception import ConnectError, RpcError

dev = Device(host='router1.example.com', user='admin', passwd='secret')

try:
    dev.open()
    result = dev.cli('show version')
    print(result)
    
except ConnectError as e:
    print(f"Connection failed: {e}")
    
except RpcError as e:
    print(f"RPC operation failed: {e}")
    
finally:
    if dev.connected:
        dev.close()

Specific Connection Error Handling

from jnpr.junos import Device
from jnpr.junos.exception import (
    ConnectAuthError, ConnectTimeoutError, ConnectUnknownHostError,
    ConnectRefusedError, ProbeError
)

dev = Device(host='router1.example.com', user='admin', passwd='secret')

try:
    # Test connectivity first
    if dev.probe(timeout=10):
        dev.open()
        print("Connected successfully")
    else:
        print("Device is not reachable")
        
except ConnectAuthError:
    print("Authentication failed - check username/password")
    
except ConnectTimeoutError:
    print("Connection timed out - device may be unreachable")
    
except ConnectUnknownHostError:
    print("Unknown host - check hostname/IP address")
    
except ConnectRefusedError:
    print("Connection refused - check NETCONF service status")
    
except ProbeError:
    print("Probe failed - network connectivity issues")
    
except ConnectError as e:
    print(f"General connection error: {e}")

Configuration Error Handling

from jnpr.junos import Device
from jnpr.junos.utils.config import Config
from jnpr.junos.exception import (
    ConfigLoadError, CommitError, LockError, UnlockError
)

dev = Device(host='router1.example.com', user='admin', passwd='secret')
dev.open()
dev.bind(cu=Config)

try:
    # Lock configuration
    dev.cu.lock()
    
    # Load configuration
    config = 'set interfaces ge-0/0/0 description "Test Interface"'
    dev.cu.load(config, format='set')
    
    # Commit configuration
    dev.cu.commit(comment='Test configuration change')
    print("Configuration committed successfully")
    
except LockError as e:
    print(f"Configuration lock failed: {e}")
    print("Database may be locked by another user")
    
except ConfigLoadError as e:
    print(f"Configuration load error: {e}")
    print("Check configuration syntax and validity")
    
except CommitError as e:
    print(f"Configuration commit failed: {e}")
    print("Detailed error information:")
    if hasattr(e, 'rpc_error'):
        for error in e.rpc_error:
            print(f"  - {error}")
    
except UnlockError:
    print("Failed to unlock configuration database")
    
finally:
    # Always attempt to unlock
    try:
        dev.cu.unlock()
    except:
        pass

dev.close()

RPC Timeout Handling

from jnpr.junos import Device
from jnpr.junos.exception import RpcTimeoutError, RpcError

dev = Device(host='router1.example.com', user='admin', passwd='secret')
dev.open()

# Set device-wide timeout
dev.timeout = 60

try:
    # Execute potentially long-running command
    result = dev.cli('show route extensive', dev_timeout=120)
    print("Command completed successfully")
    
except RpcTimeoutError:
    print("Command timed out after 120 seconds")
    print("Consider increasing timeout or using background processing")
    
except RpcError as e:
    print(f"RPC error: {e}")
    if hasattr(e, 'message'):
        print(f"Error message: {e.message}")

dev.close()

Software Management Error Handling

from jnpr.junos import Device
from jnpr.junos.utils.sw import SW
from jnpr.junos.exception import SwRollbackError, RpcTimeoutError

dev = Device(host='router1.example.com', user='admin', passwd='secret')
dev.open()
dev.bind(sw=SW)

try:
    # Attempt software installation
    result = dev.sw.install(
        package='/path/to/software.tgz',
        timeout=3600,
        validate=True
    )
    
    if result:
        print("Software installation successful")
        dev.sw.reboot()
    else:
        print("Software installation failed")
        
except SwRollbackError as e:
    print(f"Installation failed and rollback occurred: {e}")
    print("Device reverted to previous software version")
    
except RpcTimeoutError:
    print("Software installation timed out")
    print("Installation may still be in progress")
    
except FileNotFoundError:
    print("Software package file not found")
    
except Exception as e:
    print(f"Unexpected software installation error: {e}")

dev.close()

JSON Processing Error Handling

from jnpr.junos import Device
from jnpr.junos.exception import JSONLoadError
import json

dev = Device(host='router1.example.com', user='admin', passwd='secret')
dev.open()

try:
    # Get JSON output from device
    result = dev.cli('show interfaces', format='json')
    
    # Parse JSON data
    try:
        data = json.loads(result)
        print("JSON parsing successful")
        
    except json.JSONDecodeError as e:
        raise JSONLoadError(result, f"Invalid JSON format: {e}")
        
except JSONLoadError as e:
    print(f"JSON processing error: {e.message}")
    print("Raw data that failed to parse:")
    print(e.data[:200] + "..." if len(e.data) > 200 else e.data)

dev.close()

Comprehensive Error Handling

from jnpr.junos import Device
from jnpr.junos.utils.config import Config
from jnpr.junos.exception import *
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def safe_device_operation(hostname, config_data):
    """Perform device operations with comprehensive error handling."""
    dev = None
    
    try:
        # Device connection
        dev = Device(host=hostname, user='admin', passwd='secret')
        logger.info(f"Connecting to {hostname}")
        dev.open()
        
        # Bind utilities
        dev.bind(cu=Config)
        
        # Configuration operations
        logger.info("Loading configuration")
        dev.cu.lock()
        dev.cu.load(config_data, format='set')
        
        # Validate before commit
        if dev.cu.commit_check():
            logger.info("Configuration validation passed")
            dev.cu.commit(comment='Automated configuration update')
            logger.info("Configuration committed successfully")
        else:
            logger.warning("Configuration validation failed")
            
    except ConnectAuthError:
        logger.error(f"Authentication failed for {hostname}")
        return False
        
    except ConnectTimeoutError:
        logger.error(f"Connection timeout to {hostname}")
        return False
        
    except ConnectError as e:
        logger.error(f"Connection error to {hostname}: {e}")
        return False
        
    except LockError:
        logger.error(f"Configuration locked on {hostname}")
        return False
        
    except ConfigLoadError as e:
        logger.error(f"Configuration load error on {hostname}: {e}")
        return False
        
    except CommitError as e:
        logger.error(f"Configuration commit error on {hostname}: {e}")
        return False
        
    except RpcTimeoutError:
        logger.error(f"RPC timeout on {hostname}")
        return False
        
    except RpcError as e:
        logger.error(f"RPC error on {hostname}: {e}")
        return False
        
    except Exception as e:
        logger.error(f"Unexpected error on {hostname}: {e}")
        return False
        
    finally:
        if dev:
            try:
                # Cleanup operations
                if hasattr(dev, 'cu'):
                    dev.cu.unlock()
                if dev.connected:
                    dev.close()
                    logger.info(f"Disconnected from {hostname}")
            except:
                pass
    
    return True

# Usage
config = 'set system location building "Data Center 1"'
success = safe_device_operation('router1.example.com', config)

Custom Exception Handling

from jnpr.junos import Device
from jnpr.junos.exception import RpcError, ConnectError

class DeviceOperationError(Exception):
    """Custom exception for device operations."""
    
    def __init__(self, device, operation, original_error):
        self.device = device
        self.operation = operation
        self.original_error = original_error
        super().__init__(f"Operation '{operation}' failed on {device}: {original_error}")

def robust_device_operation(hostname, operation_func):
    """Wrapper for device operations with custom error handling."""
    dev = Device(host=hostname, user='admin', passwd='secret')
    
    try:
        dev.open()
        result = operation_func(dev)
        return result
        
    except (ConnectError, RpcError) as e:
        raise DeviceOperationError(hostname, operation_func.__name__, e)
        
    finally:
        if dev.connected:
            dev.close()

# Usage
def get_version_info(dev):
    return dev.cli('show version')

try:
    version = robust_device_operation('router1.example.com', get_version_info)
    print(version)
    
except DeviceOperationError as e:
    print(f"Custom error: {e}")
    print(f"Device: {e.device}")
    print(f"Operation: {e.operation}")
    print(f"Original error: {e.original_error}")

Types

# Exception base types
JunosException = Exception  # Base for all junos-eznc exceptions
ErrorMessage = str          # Error message string
ErrorCode = int            # Numeric error code

# RPC error details
RpcErrorDict = dict[str, any]  # RPC error information dictionary
RpcResponse = object           # RPC response XML element

# Connection error details
DeviceRef = object  # Reference to Device object
HostInfo = str      # Hostname or IP address

# Error context information
ErrorContext = dict[str, any]  # Additional error context data

Install with Tessl CLI

npx tessl i tessl/pypi-junos-eznc

docs

command-execution.md

configuration.md

device-connection.md

exceptions.md

facts.md

filesystem.md

index.md

operational-tables.md

software.md

tile.json