Tag: Automation

  • 🚀 How to Install Docker on Ubuntu Server (Step-by-Step Guide)

    Docker has become an essential tool for developers, system administrators, and DevOps engineers. It allows you to run applications in lightweight containers, making deployments faster, more consistent, and easier to manage.

    In this guide, you’ll learn how to install Docker on an Ubuntu server and get started with your first container.

    🧠 What is Docker?

    Docker is a containerization platform that enables you to package applications along with their dependencies into portable containers. These containers can run consistently across different environments.

    🔧 Step 1: Update Your System

    Before installing Docker, update your system packages:

    sudo apt update && sudo apt upgrade -y

    🔧 Step 2: Install Required Dependencies

    Install packages required to use HTTPS repositories:

    sudo apt install apt-transport-https ca-certificates curl software-properties-common -y

    🔐 Step 3: Add Docker’s Official GPG Key

    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor

    📦 Step 4: Add Docker Repository

    echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

    ⚙️ Step 5: Install Docker Engine

    sudo apt update
    sudo apt install docker-ce docker-ce-cli containerd.io -y

    ✅ Step 6: Verify Docker Installation

    Run the following command to test Docker:

    sudo docker run hello-world

    If Docker is installed correctly, you’ll see a confirmation message.

    🔓 Step 7: Run Docker Without sudo (Optional)

    To run Docker commands without using sudo, add your user to the Docker group:

    sudo usermod -aG docker $USER

    Then log out and log back in for the changes to take effect.

    🧩 Step 8: Install Docker Compose

    Docker Compose allows you to define and manage multi-container applications.

    sudo apt install docker-compose -y

    🌐 Step 9: Run Your First Container

    Example: Run Nginx Web Server

    docker run -d -p 8080:80 nginx

    Now open your browser and visit:

    http://<your-server-ip>:8080

    You should see the Nginx welcome page.

    🧪 Example: Run a Test Container

    docker run hello-world

    🔐 Basic Security Tips

    This verifies that Docker is working correctly.

    • Avoid exposing Docker services directly to the internet without proper security controls
    • Keep your system updated regularly
    • Use official images from trusted sources
    • Limit container privileges when possible

    💡 Useful Docker Commands

    CommandDescription
    docker psList running containers
    docker ps -aList all containers
    docker imagesList images
    docker stop <id>Stop container
    docker rm <id>Remove container

    🎯 Conclusion

    Docker simplifies application deployment by packaging everything into containers. With just a few commands, you can install Docker, run applications, and manage services efficiently.

    Whether you’re a developer, system administrator, or learner, Docker is a powerful tool worth mastering.

  • How to install OpenDaylight (ODL) on a Proxmox environment.

    🌐 What is OpenDaylight (ODL)?

    OpenDaylight (ODL) is a modular, open-source Software-Defined Networking (SDN) controller developed under the Linux Foundation.
    It acts as the central brain of a software-defined network.

    Think of ODL as a network operating system that controls switches/routers from one place using programmable APIs.


    🧠 What ODL Does

    ODL sits centrally and communicates with network devices through southbound protocols like:

    • NETCONF
    • OpenFlow
    • BGP-LS
    • PCEP
    • RESTCONF
    • gNMI

    Using these, ODL can:

    • Read device configuration
    • Push new configuration
    • Collect topology information
    • Automate network behavior
    • Build SDN applications on top

    Why ODL Is Popular

    • 100% open source
    • Supports multi-vendor hardware (Cisco, Juniper, Arista, Nokia, etc.)
    • Deep support for NETCONF/YANG (used in modern Cisco IOS-XE)
    • Full automation capabilities (northbound REST APIs)
    • Strong community and carrier-grade framework

    Used by:

    • Cisco (old Cisco OSC was based on ODL)
    • Red Hat
    • Brocade
    • Ericsson
    • AT&T

    🏗️ ODL Architecture (Simple Explanation)

    https://docs.opendaylight.org/projects/openflowplugin/en/latest/_images/plugin_arch.png
    https://www.researchgate.net/publication/317057083/figure/fig2/AS%3A496926631763968%401495487949326/The-simplified-architectural-framework-of-OpenDaylight-13.png
    • Applications
      Custom or prebuilt apps that run on top of ODL (traffic engineering, path computation, network monitoring).
    • Northbound APIs
      RESTCONF/REST APIs used by automation tools (Python, Ansible, SDN apps).
    • Controller Platform (MD-SAL)
      The Model-Driven Service Abstraction Layer.
      This is the “brain” that stores models, state, topology, and configuration.
    • Southbound Plugins
      Protocols used to talk to network devices:
      • OpenFlow
      • NETCONF
      • OVSDB
      • BGP-LS
      • PCEP

    🔧 What You Can Do With ODL

    ✔ Build full SDN topologies

    Example: OpenFlow-based switching labs.

    ✔ Automate Cisco devices using NETCONF/YANG

    ODL can act like an automation engine:

    • Push configs
    • Track device state
    • Collect data models

    ✔ Visualize network topology

    ODL automatically discovers and displays network nodes and links.

    ✔ Traffic engineering (TE) and segment routing

    Using BGP-LS and PCEP.

    ✔ Build your own SDN applications

    Example:

    • Auto-VLAN provisioning
    • Auto-QoS
    • Path optimization
    • ACL automation

    Here is the simplest and cleanest way to install OpenDaylight (ODL) on a Proxmox environment.
    You can install ODL inside a VM (Ubuntu/Debian is recommended).
    I’ll give you step-by-step commands, VM configuration, and post-installation access steps.


    1. Create a VM on Proxmox

    Use the following recommended specs:

    Recommended VM Specs

    • OS: Ubuntu Server 20.04 / 22.04 (ODL works best on 20.04)
    • CPU: 2 vCPUs
    • RAM: 4–6 GB
    • Disk: 20–30 GB
    • Network: 1 Ethernet interface (bridged or VLAN)

    OpenDaylight is Java-heavy, so do not assign < 4 GB RAM.


    🔧 2. Update the OS

    SSH into the VM / Console:

    sudo apt update && sudo apt upgrade -y
    
    

    ⚙️ 3. Install Java (ODL requires Java 11)

    sudo apt install openjdk-11-jdk -y
    
    

    Check version:

    java -version
    
    

    📦 4. Download OpenDaylight

    Download the latest stable version (Phosphorus, Sodium, or Aluminium—any works).

    cd /opt
    sudo wget https://nexus.opendaylight.org/content/groups/public/org/opendaylight/integration/distribution-karaf/0.14.4/distribution-karaf-0.14.4.tar.gz
    
    

    (Replace version if newer available.)


    📁 5. Extract the ODL package

    sudo tar -xvzf distribution-karaf-*.tar.gz
    sudo mv distribution-karaf-* opendaylight
    cd opendaylight
    
    

    ▶️ 6. Start OpenDaylight

    Run ODL:

    sudo ./bin/karaf
    
    

    This launches the Karaf console (ODL CLI).


    🧩 7. Install required ODL features

    Inside the Karaf console, install main modules:

    For OpenFlow:

    feature:install odl-restconf odl-l2switch-switch odl-openflow-plugin-all
    
    

    For NETCONF/YANG:

    feature:install odl-restconf odl-netconf-all odl-mdsal-all
    
    

    For BGP-LS / PCEP:

    feature:install odl-bgpcep-bgp odl-bgpcep-pcep
    
    

    🌐 8. Access Web UI (DLUX)

    Enable DLUX:

    feature:install odl-dlux-all
    
    

    Open your browser:

    http://<VM-IP>:8181/index.html#/login
    
    

    Default credentials:

    username: admin
    password: admin
    
    

    🔄 9. Run ODL as a service (recommended)

    Exit Karaf (Ctrl + D)

    Create a systemd service:

    sudo nano /etc/systemd/system/opendaylight.service
    
    

    Paste:

    [Unit]
    Description=OpenDaylight SDN Controller
    After=network.target
    
    [Service]
    User=root
    ExecStart=/opt/opendaylight/bin/karaf
    Restart=on-abort
    
    [Install]
    WantedBy=multi-user.target
    
    

    Enable + start:

    sudo systemctl daemon-reload
    sudo systemctl enable opendaylight
    sudo systemctl start opendaylight
    sudo systemctl status opendaylight
    
    

    🎉 ODL is now running on Proxmox!


    📌 Bonus: Integrate ODL with Cisco Devices

    If using NETCONF:

    feature:install odl-restconf odl-netconf-all
    
    

    Then add your Cisco device:

    PUT http://<ODL-IP>:8181/restconf/config/network-topology:network-topology/topology/topology-netconf/node/<device-name>
    
    

    If using OpenFlow, make sure the switch points to ODL:

    openflow controller x.x.x.x port 6633 vrf <name>
    
  • The Silent Cost: Underutilization of Assets and Tools in Organizations

    In today’s cloud-first world, organizations spend millions on security, compliance, and infrastructure tools — yet most use less than 50% of their potential.
    This underutilization isn’t just wasted investment — it’s a missed opportunity to optimize, automate, and secure the digital ecosystem.

    🚨 The Reality of Tool Sprawl
    From CSPM, SPM, and Infrastructure Security to BUA , tech stacks are growing faster than adoption.

    Many enterprises:

    • Keep buying new tools instead of optimizing existing ones,
    • Overlook built-in features in Microsoft, AWS, or Azure,
    • Ignore capable open-source alternatives, and
    • Struggle with low tool adoption in operations due to lack of integration or enablement.

    The result? Expensive tools delivering minimal outcomes.


    🔍 Hidden Potential Across Key Areas

    • CSPM: Used mainly for visibility, while automation, remediation, and multi-cloud correlation stay idle.
    • SPM: Focused on dashboards, rarely integrated with ITSM or DevOps to catch compliance drifts early.
    • Infrastructure Security: Tools like Tufin, Skybox, or Lacework offer strong analytics but are seldom linked to CI/CD or workflow automation.


    🧩 The Open-Source Gap
    Many organizations purchase costly solutions when powerful open-source options like Terrascan,Trivy, Terrascan, Falco, OSQuery, Rsyslog,Prometheus, or OpenVAS already exist.
    These tools offer:

    • Deep configurability,
    • Smooth CI/CD integration, and
    • Strong community support.

    Yet, they’re often ignored or only partially adopted — leaving huge value untapped.


    💡 Shifting the Mindset

    Instead of expanding toolsets, focus on maximizing existing capabilities:

    • Conduct Tool Utilization Audits.
    • Evaluate open-source before buying new tools.
    • Train teams to use advanced features.
    • Automate posture insights within DevSecOps pipelines.

    The goal isn’t to have more tools — it’s to make existing ones work smarter together.


    ⚙️ The Way Forward
    Before investing in another platform, ask:
    “Are we fully using what we already have — or paying twice for the same capability?”
    Optimizing assets and leveraging open-source innovation can reduce costs, improve visibility, and strengthen cloud security posture.
    In cybersecurity today, optimization is the new innovation — and efficiency is the new defense.


    💬 What’s your view?
     Have you seen costly tools purchased while open-source alternatives sit idle? How can organizations empower operations teams to bridge this gap?


    #CloudSecurity #CSPM hashtag#SPM #InfraSecurity #DevSecOps #CloudGovernance #OpenSource #Freeware #ToolOptimization #SecurityPosture #Azure hashtag#AWS #CostOptimization #SecurityAutomation


    hashtag#CloudSecurity hashtag#CSPM hashtag#SPM hashtag#InfraSecurity hashtag#DevSecOps hashtag#CloudGovernance hashtag#OpenSource hashtag#Freeware hashtag#ToolOptimization hashtag#SecurityPosture hashtag#Azure hashtag#AWS hashtag#CostOptimization hashtag#SecurityAutomation

  • 🧠 What is AI and ML in Networking?

    Artificial Intelligence (AI) and Machine Learning (ML) in networking refer to the use of data-driven algorithms and automation to make networks smarter, self-learning, and self-optimizing.

    In simple terms —
    👉 AI/ML help networks think, learn, and act on their own instead of relying only on human intervention.

    For example:

    • The network can detect anomalies, predict failures, or optimize routing automatically — based on continuous data analysis.

    ⚙️ Why AI/ML Are Needed in Networking

    Modern networks are:

    • Massive (thousands of devices, millions of connections)
    • Dynamic (cloud, IoT, 5G, SDN)
    • Complex (virtual + physical + security layers)

    Traditional manual management can’t keep up.
    AI and ML provide automation, intelligence, and adaptability to handle this complexity efficiently.


    🧩 Key Applications of AI/ML in Networking

    1. Network Automation

    • AI helps in automatically configuring, optimizing, and healing networks.
    • ML models learn from network data and predict optimal configurations.

    Example:
    Automatically adjusting QoS or bandwidth based on traffic patterns.


    2. Predictive Maintenance

    • ML algorithms analyze device logs, performance metrics, and temperature data to predict failures before they happen.

    Example:
    AI predicts a switch port failure based on rising CRC errors and triggers proactive replacement.


    3. Anomaly Detection and Security

    • AI detects unusual traffic patterns that may indicate cyberattacks, malware, or misconfigurations.
    • ML models can learn what “normal” behavior looks like and alert when deviations occur.

    Example:
    Detecting a DDoS attack based on sudden traffic spikes.


    4. Traffic Analysis and Optimization

    • ML helps to analyze traffic flows and dynamically reroute data for better performance.
    • Can optimize latency, throughput, and load balancing.

    Example:
    AI-driven SD-WAN controllers automatically select the best WAN link per application.


    5. Quality of Experience (QoE) Enhancement

    • AI monitors user experience (e.g., video call quality) and adjusts parameters like jitter, latency, and bandwidth in real time.

    6. Network Planning and Capacity Forecasting

    • ML models analyze growth trends and predict future capacity needs.
    • Useful for ISP and data center planning.

    7. Intent-Based Networking (IBN)

    • The network understands high-level intent (“ensure low latency for voice traffic”) and uses AI/ML to translate it into actual configurations and policies automatically.

    🧱 AI/ML in Networking Architecture

    LayerFunctionExample
    Data CollectionCollect telemetry, logs, SNMP, NetFlow, SyslogNetwork devices, sensors
    Data ProcessingClean, normalize, and store dataStreaming analytics platforms
    Machine Learning EngineTrain models, detect patterns, make predictionsTensorFlow, Scikit-learn
    Automation LayerTake actions (config updates, alerts, rerouting)Ansible, SDN controller
    Visualization LayerDisplay analytics and decisionsDashboards, reports

    🧠 AI Techniques Used in Networking

    TechniquePurposeExample
    Supervised LearningPredict outcomes from labeled dataPredict link failures
    Unsupervised LearningDetect patterns or anomaliesNetwork anomaly detection
    Reinforcement LearningLearn best actions via trial and feedbackAdaptive routing
    Deep Learning (Neural Networks)Handle large and complex dataVideo QoS optimization
    Natural Language Processing (NLP)Understand text/voice inputChatbots for network operations (NetOps assistants)

    🧰 Real-World AI-Driven Networking Tools

    VendorPlatformAI/ML Capability
    Cisco DNA CenterAI Network AnalyticsClient health, anomaly detection, insights
    Juniper Mist AIAI-driven WLANPredictive Wi-Fi troubleshooting
    Arista CloudVisionAI TelemetryNetwork state analysis
    VMware vRealize Network InsightNetwork analyticsFlow visibility and optimization
    Fortinet FortiAISecurity AIMalware detection and behavioral analysis

    🌐 Benefits of AI/ML in Networking

    • Self-Healing Networks: Automatically detect and fix issues
    • Proactive Maintenance: Prevent outages before they occur
    • Reduced Downtime: Faster troubleshooting and resolution
    • Better Security: Identify new attack patterns
    • Improved Performance: Optimize bandwidth and routing
    • Cost Efficiency: Reduce manual work and operational overhead

    🚧 Challenges

    • Data Quality: Inaccurate or incomplete data leads to wrong predictions
    • Integration: Legacy systems may not support modern APIs
    • Explainability: Hard to understand ML model decisions
    • Security: AI systems themselves must be protected

    🏗️ Example Use Case

    Scenario: Enterprise WAN Optimization

    1. Routers and switches send telemetry to a central AI engine.
    2. The ML model analyzes traffic latency, loss, and jitter.
    3. AI identifies congestion and predicts peak hours.
    4. The SDN controller reroutes traffic proactively to maintain SLA.

    Result → Better performance, fewer complaints, and automated control.


    🧭 Summary

    ConceptDescription
    AI in NetworkingSystems that make intelligent decisions automatically
    ML in NetworkingAlgorithms that learn patterns from network data
    Use CasesFault prediction, anomaly detection, optimization
    BenefitsAutomation, efficiency, reliability, cost reduction
    Key ToolsCisco DNA Center, Juniper Mist AI, VMware NSX, FortiAI
  • 🧠 What is a REST API?

    REST API stands for Representational State Transfer Application Programming Interface.
    It’s a standard way for two systems to communicate over the web (HTTP/HTTPS) — often between a client (like Python script or Ansible) and a server (like a network device or SDN controller).

    In simple terms:
    👉 A REST API allows you to interact with a system (get data, configure, update, or delete something) using HTTP requests — just like how your browser communicates with websites.


    ⚙️ Why REST APIs Matter in Networking

    In modern networks:

    • Devices (Cisco, Juniper, Fortinet, etc.) and controllers (like OpenDaylight, Cisco DNA Center, VMware NSX) expose REST APIs.
    • Engineers can automate tasks (like getting interface status, pushing configurations, or monitoring health) using API calls instead of manual CLI.

    Example:
    Instead of logging into 50 routers to check interface status,
    you can run one Python script that uses REST APIs to fetch all interface data.


    🧩 Key Concepts of REST API

    ConceptDescription
    ClientThe system or application making the API request (e.g., Python script, Postman, Ansible)
    ServerThe system that provides the API (e.g., router, firewall, controller)
    ResourceThe object you’re working with (e.g., interface, VLAN, route, policy)
    URI (Uniform Resource Identifier)The address to access a resource (e.g., /api/v1/interfaces)
    HTTP MethodsDefine what action to perform on a resource

    🔠 Common HTTP Methods

    MethodPurposeExample
    GETRetrieve informationGet interface status
    POSTCreate new data/configurationAdd a new VLAN
    PUTUpdate/replace dataChange an interface IP
    PATCHModify part of a resourceUpdate interface description
    DELETERemove data/configurationDelete a VLAN

    🧾 Typical REST API Request Structure

    A REST API request looks like this:

    Method: GET
    URL: https://192.168.1.1/api/v1/interfaces
    Headers:
        Content-Type: application/json
        Authorization: Bearer <token>
    
    

    Response (from device or server):

    {
      "interfaces": [
        {"name": "GigabitEthernet0/0", "status": "up"},
        {"name": "GigabitEthernet0/1", "status": "down"}
      ]
    }
    
    

    💡 Key Characteristics of REST APIs

    • Stateless: Each request is independent; the server doesn’t remember previous ones.
    • Uses HTTP verbs: GET, POST, PUT, DELETE, etc.
    • Uses URIs to identify resources.
    • Supports multiple data formats: Commonly JSON, sometimes XML.
    • Client-Server separation: Clear boundary between what requests and what responds.
    • Cacheable: Responses can be cached for performance.

    🧰 Common Tools to Work with REST APIs

    ToolUse
    PostmanGUI-based tool to test and visualize API calls
    cURLCommand-line tool for sending HTTP requests
    Python (Requests library)Programmatically interact with APIs
    Ansible / TerraformUse APIs for automation/infrastructure as code

    🐍 Example: Python Script Using REST API

    import requests
    import json
    
    url = "https://192.168.1.1/api/v1/interfaces"
    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer your_token_here"
    }
    
    response = requests.get(url, headers=headers, verify=False)
    data = response.json()
    
    for interface in data["interfaces"]:
        print(interface["name"], "-", interface["status"])
    
    

    ✅ This script retrieves interface status from a network device that supports REST APIs.


    🌐 Example REST API Endpoints (Networking)

    VendorAPI ExampleDescription
    Cisco DNA Center/dna/intent/api/v1/network-deviceGet all devices
    Fortinet FortiGate/api/v2/monitor/system/interface/Get interface list
    Juniper Junos/rpc/get-interface-informationGet interface info
    OpenDaylight/restconf/operational/network-topology:network-topologyGet network topology
    Arista eAPI/command-apiSend CLI commands via JSON-RPC

    Benefits of Using REST APIs

    • Automation: Eliminate manual configuration
    • Integration: Connect network, cloud, and monitoring systems
    • Speed: Fast configuration and data collection
    • Consistency: Apply uniform settings across devices
    • Scalability: Manage hundreds of devices easily

    🧭 Summary

    ConceptDescription
    Full FormRepresentational State Transfer API
    PurposeCommunication between client and server using HTTP
    Data FormatJSON / XML
    Common MethodsGET, POST, PUT, DELETE
    Use in NetworkingAutomate configuration, monitoring, and integration
    ToolsPostman, Python Requests, Ansible
  • How to enable Meraki API

    The Meraki API allows you to automate and manage your Meraki network programmatically. It is a RESTful API that provides access to Meraki dashboard data and configurations.


    1. Enable Meraki API

    Before using the API, you must enable it in the Meraki Dashboard:

    • Login to Meraki Dashboarddashboard.meraki.com
    • Go to “Organization” > “Settings”
    • Scroll to “Dashboard API access” and toggle it ON.
    • Click “Save”.

    2. Generate an API Key

    • Go to “My Profile” (top-right corner in the dashboard).
    • Scroll to “API access”.
    • Click “Generate API Key”.
    • Copy and save the API Key (It won’t be shown again).

    ⚠️ Security Note: Treat your API key like a password—never expose it in public or store it in unsecured locations.


    3. Test API Connectivity

    Use Postman or cURL to test API access.

    Example: Get Organization List

    Using cURL:

    curl -L -H "X-Cisco-Meraki-API-Key: YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -X GET "https://api.meraki.com/api/v1/organizations"

    Using Python:

    import requests

    API_KEY = "YOUR_API_KEY"
    url = "https://api.meraki.com/api/v1/organizations"

    headers = {
    "X-Cisco-Meraki-API-Key": API_KEY,
    "Content-Type": "application/json"
    }

    response = requests.get(url, headers=headers)
    print(response.json())

    4. Common Meraki API Endpoints

    Here are some useful endpoints:

    Organization Management

    ActionMethodEndpoint
    List organizationsGET/organizations
    Get org detailsGET/organizations/{orgId}
    Claim devices to orgPOST/organizations/{orgId}/claim

    Network Management

    ActionMethodEndpoint
    List networksGET/organizations/{orgId}/networks
    Create a networkPOST/organizations/{orgId}/networks
    Delete a networkDELETE/networks/{networkId}

    Device Management

    ActionMethodEndpoint
    List devices in a networkGET/networks/{networkId}/devices
    Get device detailsGET/devices/{serial}
    Update device settingsPUT/devices/{serial}

    5. Advanced Usage

    • Meraki Python SDK: Use the official Meraki Python library for easier API calls. bashCopyEditpip install meraki pythonCopyEditimport meraki API_KEY = "YOUR_API_KEY" dashboard = meraki.DashboardAPI(API_KEY) orgs = dashboard.organizations.getOrganizations() print(orgs)
    • Webhooks: Configure webhooks for real-time alerts.
    • Automation: Automate network provisioning, VLAN assignments, SSID management, etc.

    6. API Documentation

    For a complete list of API endpoints, visit Meraki API Docs.

  • Python script to check the Cisco IOS version and perform upgrades or downgrades as needed

    This script will utilize the Netmiko library for SSH connections and the NAPALM library for device configuration management.

    Script Requirements

    1. Python 3.x
    2. Netmiko library (install using pip install netmiko)
    3. NAPALM library (install using pip install napalm)
    4. Cisco IOS device(s) with SSH enabled
    5. A configuration file (e.g., config.yaml) defining the recommended IOS versions for each device model
    6. A directory containing the IOS image files (e.g., images/) matching the device models and recommended versions

    Script Structure

    The script will consist of the following components:

    1. Device Connection: Establish an SSH connection to the Cisco device using Netmiko.
    2. IOS Version Check: Retrieve the current IOS version from the device using NAPALM.
    3. Configuration Check: Compare the current IOS version with the recommended version defined in the configuration file.
    4. Upgrade/Downgrade: Perform the necessary upgrade or downgrade using NAPALM, if the current version does not match the recommended version.
    5. Image Transfer: Transfer the required IOS image file from the images/ directory to the device using SCP (or other transfer method).

    Script Code

    Here’s a sample script to get you started:

    import os
    import yaml
    from netmiko import SSHNetmiko
    from napalm.base import get_network_driver
    
    # Configuration file path
    config_file = 'config.yaml'
    
    # Device model to IOS image mapping
    device_models = {
        'WS-C3560X-48P': 'c3560e-universalk9-mz.122-55.SE8.bin'
    }
    
    # Recommended IOS versions for each device model
    recommended_versions = {
        'WS-C3560X-48P': '15.2(4)E8'
    }
    
    def get_current_ios_version(device):
        # Establish SSH connection using Netmiko
        ssh = SSHNetmiko(device['ip'], username='your_username', password='your_password')
        # Retrieve current IOS version using NAPALM
        ios_version = ssh.get_facts()['ios_version']
        return ios_version
    
    def check_ios_version(current_version, recommended_version):
        if current_version != recommended_version:
            return True  # Version mismatch, upgrade/downgrade required
        return False  # Version matches, no action needed
    
    def upgrade_or_downgrade(device, current_version, recommended_version):
        # Determine upgrade/downgrade direction
        if current_version < recommended_version:
            direction = 'upgrade'
        elif current_version > recommended_version:
            direction = 'downgrade'
        else:
            return  # No action needed
    
        # Transfer required IOS image file using SCP
        image_file = os.path.join('images/', device_models[device['model']])
        ssh.scp.put(image_file, '/tmp/')
    
        # Perform upgrade/downgrade using NAPALM
        if direction == 'upgrade':
            ssh.load_replace_candidate(filename='/tmp/' + image_file)
            ssh.commit_config()
        elif direction == 'downgrade':
            ssh.load_replace_candidate(filename='/tmp/' + image_file, replace='exact')
            ssh.commit_config()
    
        # Reload the device to apply changes
        ssh.send_command('reload')
    
    def main():
        with open(config_file, 'r') as f:
            config_data = yaml.safe_load(f)
    
        for device in config_data['devices']:
            current_version = get_current_ios_version(device)
            recommended_version = recommended_versions[device['model']]
            if check_ios_version(current_version, recommended_version):
                upgrade_or_downgrade(device, current_version, recommended_version)
    
    if __name__ == '__main__':
        main()

    Note

    1. Replace your_username and your_password with your actual SSH credentials.
    2. Update the device_models dictionary to match your specific device models and corresponding IOS image files.
    3. Modify the recommended_versions dictionary to reflect the desired IOS versions for each device model.
    4. Ensure the images/ directory contains the required IOS image files.
    5. This script is a starting point and may require additional error handling, logging, and testing to ensure its reliability.

    Remember to test the script in a lab environment before deploying it to production 🙂

  • Python Script to Execute Show Commands in Multiple Devices and Save the Output to a Text File

    The script requires two text files, put your device IP addresses in IPAddressList.txt and create another blank file named Command_Output.txt in the application directory .

    Prerequisites

    • Python 3
    • Paramiko

    from future import print_function
    from netmiko import ConnectHandler
    import os
    import sys
    import time
    import select
    import paramiko
    import re

    fd = open(‘r’\home\user\Command_Output.txt’,’w’)
    old_stdout = sys.stdout
    sys.stdout = fd
    platform = ‘cisco_ios’
    username = ‘XXXX’
    password = ‘XXXX’
    ip_add_file = open(r’\home\user\IPAddressList.txt’,’r’)

    for host in ip_add_file:
    #host = host.strip()
    device = ConnectHandler(device_type=platform, ip=host, username=username, password=password)
    output = device.send_command(‘sh int trunk’)
    print(output)

    fd.close()

  • Simple Batch Script for Changing Proxy Options

    When we take our office laptop to home the main headache is changing the  proxy settings to access internet. Download the zip file unzip it into a folder there are two files, one for Turnoff Proxy another for Turn on Proxy.

    Download Link —-> Proxy

     

    Proxy1

    Enjoy 🙂 🙂

  • Simple Batch Script for Ping Sweep

    This is a tiny batch script to check live hosts in network . Download the zip file and unzip contents to a folder and put your device names in servers.txt file.  After that Run the script file it will do ping test and save the output in results.txt file.

    Download  link —->    Ping Script

    Ping1Ping2Ping3Ping4

    If you have any doubt please reach out to me 🙂 🙂