Setting Up Python Environments for EOS Interaction #
Why Am I Writing This? #
Welcome back to Part 2 of “Basic Python with EOS for Network Engineers.” If you stuck around after Part 1, you must be serious about this whole automation thing. Good on you. In my military days, we’d already be knee-deep in the trenches by now, but I promise this setup phase is worth your time. Let’s build an environment that won’t fall apart when you need it most.
Python Virtual Environments: The Networking Dood’s Sanity Saver #
Why Should I Care About Virtual Environments? #
Think of virtual environments like separate containers for your different network projects. Much like how I kept Wolfenstein 3D hidden from my grandmother back in the day, these environments keep your dependencies hidden from each other.
Here’s why they’re worth the extra setup:
- No dependency drama: One project needs pyeapi 0.8.4, another needs 0.9.0? No problem.
- Easy replication: Build once, deploy anywhere (well, almost)
- Safe testing: Blow it all up without affecting your production tools
- Resume-worthy skills: Nothing says “modern network engineer” like proper environment management
Setting It Up #
Let’s get a virtual environment going:
# Install virtualenv if you haven't already
brew install virtualenv
# Create a dedicated space for your EOS automation
mkdir eos-automation
cd eos-automation
python -m venv venv
# Activate it (your terminal prompt should change)
# Windows folks:
venv\Scripts\activate
# Linux/macOS people:
source venv/bin/activate
# Now you're in the matrix
(venv) $
Managing Your Requirements #
When I was the network architect for that base with 150K users, organization was critical. The same applies here - no random, untracked dependencies. Let’s be professional:
# Create a requirements.txt file with what we need
echo "pyeapi>=0.8.4
netmiko>=4.1.0
pyyaml>=6.0
requests>=2.28.1
jsonrpclib>=0.4.3.2" > requirements.txt
# Install everything in one shot
pip install -r requirements.txt
Essential Libraries: The Tools in Your Networking Toolbox #
pyeapi: The Arista Whisperer #
This is Arista’s official Python client. It’s like having a direct line to your switch’s brain:
pip install pyeapi
Why it’s awesome:
- Speaks directly to the eAPI
- Returns data in Python dictionaries (your new best friend)
- Handles connections efficiently
- Made by Arista, for Arista (no third-party shenanigans)
Netmiko: The SSH Swiss Army Knife #
Sometimes you need to fall back to SSH. Netmiko has your back:
pip install netmiko
I’ve used this across countless vendors, and it’s saved me during those “the API is down but I still need to make changes” scenarios.
The Supporting Cast #
These might seem like extras, but trust me, you’ll need them:
# For making HTTP requests like a boss
pip install requests
# For handling configs in a sane way
pip install pyyaml
# For JSON-RPC when you need it
pip install jsonrpclib-pelix
Connecting to EOS: Let’s Make Friends with Your Switches #
The eAPI Way (Preferred) #
eAPI is how the cool kids talk to Arista devices. It’s fast, structured, and powerful:
import pyeapi
# Method 1: Using a config file (my preference for production)
node = pyeapi.connect_to('switch1')
# Method 2: The explicit way
connection = pyeapi.connect(
transport='https',
host='192.168.1.1', # Your switch IP goes here
username='admin', # Don't use 'admin' in production. Seriously.
password='arista123', # Please tell me this isn't your actual password
port=443
)
# Run some commands and see what comes back
output = connection.enable(['show version', 'show interfaces'])
print(output[0]['result']) # Just the show version results
The SSH Fallback #
Sometimes you can’t use eAPI. Maybe it’s disabled, maybe your security team has concerns, or maybe you just enjoy the pain of parsing unstructured text (no judgment here):
from netmiko import ConnectHandler
# Setup your device details
arista_device = {
'device_type': 'arista_eos',
'host': '192.168.1.1',
'username': 'admin', # Again, not in production
'password': 'arista123', # Sigh...
'port': 22
}
# Connect and do stuff
with ConnectHandler(**arista_device) as conn:
# Get some info
output = conn.send_command('show version')
print(output)
# Make some changes
config_commands = [
'interface Ethernet1',
'description Configured by Python because NetworkDood said so'
]
conn.send_config_set(config_commands)
Security: Because Getting Hacked Isn’t on My Bucket List #
Credential Management: Don’t Be That Engineer #
I’ve seen way too many credentials hardcoded in scripts. Please, for the love of all things networky, don’t do this. Instead:
- Environment Variables:
import os
username = os.environ.get('EOS_USERNAME')
password = os.environ.get('EOS_PASSWORD')
- Configuration Files:
# ~/.eapi.conf
[connection:switch1]
host: 192.168.1.1
username: admin
password: arista123
transport: https
- Secret Management Tools:
# Using keyring
import keyring
username = 'admin'
password = keyring.get_password('eos_devices', username)
Certificate Verification #
I learned about certificate importance the hard way in Afghanistan. Trust me on this one:
# Do this in production
connection = pyeapi.connect(
transport='https',
host='192.168.1.1',
username='admin',
password='arista123',
port=443,
verify=True # Verify those certs!
)
# For special cases with internal CAs
connection = pyeapi.connect(
transport='https',
host='192.168.1.1',
username='admin',
password='arista123',
port=443,
verify='/path/to/ca-bundle.crt' # Your company's CA bundle
)
Testing: Is This Thing On? #
The “Can I Connect?” Test #
Create a simple script called test_connection.py. This will tell you if your basic setup is working:
import pyeapi
import sys
def test_eos_connection(hostname, username, password):
try:
# Try to connect
connection = pyeapi.connect(
transport='https',
host=hostname,
username=username,
password=password,
port=443
)
# Run a basic command
response = connection.enable(['show version'])
version = response[0]['result']['version']
model = response[0]['result']['modelName']
print(f"✅ Connection successful!")
print(f"Device: {model} running EOS version {version}")
return True
except Exception as e:
print(f"❌ Connection failed: {str(e)}")
return False
if __name__ == "__main__":
if len(sys.argv) != 4:
print("Usage: python test_connection.py <hostname> <username> <password>")
sys.exit(1)
hostname = sys.argv[1]
username = sys.argv[2]
password = sys.argv[3]
test_eos_connection(hostname, username, password)
Run it like this:
python test_connection.py 192.168.1.1 admin arista123
The “Is My Environment Complete?” Script #
After 11 years at my company, I’ve learned the importance of checking everything before deploying. Here’s a script that would have saved me countless troubleshooting hours:
def verify_environment():
import sys
import subprocess
import pkg_resources
# Python version check
python_version = sys.version_info
print(f"Python version: {python_version.major}.{python_version.minor}.{python_version.micro}")
if python_version.major < 3 or (python_version.major == 3 and python_version.minor < 6):
print("⚠️ WARNING: Python 3.6+ recommended for EOS automation")
# Packages we need to make the magic happen
required_packages = {
'pyeapi': '0.8.4',
'netmiko': '4.1.0',
'pyyaml': '6.0',
'requests': '2.28.1'
}
# Check each one
missing_packages = []
outdated_packages = []
for package, min_version in required_packages.items():
try:
installed_version = pkg_resources.get_distribution(package).version
print(f"✅ {package} version {installed_version} installed")
if pkg_resources.parse_version(installed_version) < pkg_resources.parse_version(min_version):
outdated_packages.append((package, installed_version, min_version))
except pkg_resources.DistributionNotFound:
print(f"❌ {package} not installed")
missing_packages.append(package)
# Tell me what's wrong
if missing_packages:
print("\n⚠️ Missing packages:")
for package in missing_packages:
print(f" - {package}")
print("\nInstall with: pip install " + " ".join(missing_packages))
if outdated_packages:
print("\n⚠️ Outdated packages:")
for package, installed, recommended in outdated_packages:
print(f" - {package}: installed={installed}, recommended={recommended}")
print("\nUpdate with: pip install --upgrade " + " ".join([p[0] for p in outdated_packages]))
if not missing_packages and not outdated_packages:
print("\n✅ Environment check passed! You're ready to automate EOS devices.")
if __name__ == "__main__":
verify_environment()
Project Structure: Because Organization Matters #
A little structure goes a long way. Here’s how I organize my EOS automation projects:
eos-automation/
├── venv/ # Your virtual environment
├── requirements.txt # Your dependencies
├── config/
│ ├── credentials.yml # Encrypted or excluded from git!
│ ├── devices.yml # Your device inventory
│ └── templates/ # Jinja2 templates for configs
├── scripts/
│ ├── backup_configs.py # Save yourself when things go wrong
│ ├── deploy_vlans.py # VLAN deployment script
│ └── audit_interfaces.py # Find those misconfigurations
├── lib/
│ ├── __init__.py
│ ├── eos_connector.py # Connection handling
│ └── utils.py # Utility functions
├── tests/ # Test before you deploy!
│ ├── test_connection.py
│ └── test_config_deploy.py
└── README.md # Document or regret it later
Wrapping Up #
I’ve spent years learning this stuff through trial and error—and a lot of errors at that. This setup will save you time and prevent the same headaches I had. Trust me, future you will thank present you for taking the time to set this up right.
Next up in Part 3, we’ll actually use this environment to do some real work with eAPI. That’s where the fun begins!
Resources to Keep You Going #
- Official pyeapi Documentation
- Arista EOS API Guide
- Netmiko Documentation
- Python Virtual Environments Tutorial
- NetworkDood Articles - Check back for the next article in this series!