Header Ads Widget

Responsive Advertisement

Python Click CLI utility to add device/view devices listed in inventory/delete device entry from device Inventory

 Creating/modifying  a device Inventory list CLI using the python click framework is one of   the easiest  way. Here's how we can build a CLI tool step-by-step:


 1. Add Device: Create inventory file , created if does not exits
 2. Save Inventory file:  Save the file 
 3. Add Device: Add a new device to the inventory
 4.View Inventory: List all devices in the inventory.
 5.Search Device: Search for a device by name or IP.
 6.Delete Device: Remove a device from the inventory.
 7.Export Inventory: Save the inventory to a file (CSV or JSON).

 Sample Code :

    """
 1. File to store device inventory ( Specific path can be defined)
    # Load existing inventory or create an empty one
"""
INVENTORY_FILE = Path("network_inventory.json")

def load_inventory():
    if INVENTORY_FILE.exists():
        with open(INVENTORY_FILE, "r") as f:
            return json.load(f)
    return []

"""
2. Save inventory  file
"""
def save_inventory(inventory):
    with open(INVENTORY_FILE, "w") as f:
        json.dump(inventory, f, indent=4)

@click.group()
def cli():
    """Network Device Inventory CLI"""
    pass

"""
3. Add devices
"""
@click.command()
@click.option('--name', prompt="Enter Device Name", help="Name of the device.")
@click.option('--ip', prompt="Enter Device IP", help=" IP address of the device.")
@click.option('--type', prompt="Enter Device Type", help="The type of the device (e.g., Router, Switch, Firewall, Nexus, ACI, SDWAN).")

def add_device(name, ip, type):
    """Add a new device to the inventory."""
    inventory = load_inventory()
    inventory.append({"name": name, "ip": ip, "type": type})
    save_inventory(inventory)
    click.echo(f"Device '{name}' added successfully!")

"""
4. view devices present in invertory
"""
@click.command()

def view_inventory():
    """View all devices in the inventory."""
    inventory = load_inventory()
    if not inventory:
        click.echo("No devices found in inventory.")
        return
    click.echo("Current Inventory:")
    for device in inventory:
        click.echo(f"- Name: {device['name']}, IP: {device['ip']}, Type: {device['type']}")

"""
5. search devices present in invertory
"""        

@click.command()
@click.option('--search', prompt="Search term", help="Search by device name or IP.")

def search_device(search):
    """Search for a device by name or IP."""
    inventory = load_inventory()
    results = [device for device in inventory if search in device['name'] or search in device['ip']]
    if results:
        click.echo("Search Results:")
        for device in results:
            click.echo(f"- Name: {device['name']}, IP: {device['ip']}, Type: {device['type']}")
    else:
        click.echo(f"No devices found matching '{search}'.")

"""
6. Delete device from the invertory
"""

@click.command()
@click.option('--name', prompt="Device Name", help="The name of the device to delete.")

def delete_device(name):
    """Delete a device from the inventory."""
    inventory = load_inventory()
    updated_inventory = [device for device in inventory if device['name'] != name]
    if len(inventory) == len(updated_inventory):
        click.echo(f"No device found with the name '{name}'.")
        return
    save_inventory(updated_inventory)
    click.echo(f"Device '{name}' deleted successfully.")

"""
7. Export device to Inverntory  
"""
@click.command()
@click.option('--format', type=click.Choice(['csv', 'json']), prompt="Export format (csv/json)",
              help="Format to export the inventory.")
@click.option('--output', prompt="Output file name", help="File to save the exported inventory.")

def export_inventory(format, output):
    """Export the inventory to a file."""
    inventory = load_inventory()
    if format == "json":
        with open(output, "w") as f:
            json.dump(inventory, f, indent=4)
        click.echo(f"Inventory exported to '{output}' in JSON format.")
    elif format == "csv":
        with open(output, "w", newline='') as f:
            writer = csv.DictWriter(f, fieldnames=["name", "ip", "type"])
            writer.writeheader()
            writer.writerows(inventory)
        click.echo(f"Inventory exported to '{output}' in CSV format.")

"""
8. Register commands with CLI group
"""

cli.add_command(add_device)
cli.add_command(view_inventory)
cli.add_command(search_device)
cli.add_command(delete_device)
cli.add_command(export_inventory)


"""
Execution
"""

if __name__ == "__main__":
    cli()
  


 CLI Execution :

   Options available in CLI :


CLI Options 

   Device addition by CLI :




   Device View : 


   Device Deletion via CLI:










 








  

   
   
 


    



   
   






Post a Comment

0 Comments