Azure Security Center Management Client Library

7.0.0 · active · verified Thu Apr 09

The Azure Security Center Management Client Library for Python provides the necessary tools to interact with Microsoft Defender for Cloud (formerly Azure Security Center). It allows for programmatically managing security policies, alerts, and other security-related resources within Azure. The current stable version is 7.0.0. Azure SDKs typically follow a regular release cadence, with minor updates several times a year and major versions released as needed for significant breaking changes or new API versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to authenticate with Azure using `DefaultAzureCredential` and create an instance of the `SecurityCenter` client. It then lists the security policies and the first few alerts associated with the specified Azure subscription. Ensure your `AZURE_SUBSCRIPTION_ID` environment variable is set and you are authenticated to Azure (e.g., via `az login` for local development).

import os
from azure.identity import DefaultAzureCredential
from azure.mgmt.security import SecurityCenter

# Set your Azure Subscription ID as an environment variable, e.g., AZURE_SUBSCRIPTION_ID
subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "YOUR_SUBSCRIPTION_ID")

if subscription_id == "YOUR_SUBSCRIPTION_ID":
    print("Please set the AZURE_SUBSCRIPTION_ID environment variable.")
    exit(1)

try:
    # Authenticate using DefaultAzureCredential
    # This credential chain will attempt to authenticate in various environments
    # (e.g., environment variables, managed identity, Azure CLI, Visual Studio Code)
    credential = DefaultAzureCredential()

    # Create a SecurityCenterManagementClient
    security_client = SecurityCenter(credential=credential, subscription_id=subscription_id)

    # Example: List security policies for a subscription
    print(f"Listing security policies for subscription: {subscription_id}")
    policies = security_client.security_policies.list()

    for policy in policies:
        print(f"  Policy Name: {policy.name}, Type: {policy.policy_type}")

    print("\nListing alerts (first few, if any):")
    alerts_iterator = security_client.alerts.list()
    first_five_alerts = []
    for i, alert in enumerate(alerts_iterator):
        if i >= 5:
            break
        first_five_alerts.append(alert)
        print(f"  Alert: {alert.name}, State: {alert.status}, Severity: {alert.severity}")
    if not first_five_alerts:
        print("  No alerts found.")

except Exception as e:
    print(f"An error occurred: {e}")
    print("Ensure you have set AZURE_SUBSCRIPTION_ID and configured authentication (e.g., via Azure CLI 'az login').")

view raw JSON →