如何使用Python将子网与Azure中的网络安全组关联?

2024-03-29 09:17:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有python函数,它创建了新的网络安全组:

def createNetworkSecurityGroup(subscription, location, resourceGroupName, networkSecurityGroupName, headers):
    print(f'Creating networking security group {networkSecurityGroupName}...')
    # https://docs.microsoft.com/en-us/rest/api/virtualnetwork/networksecuritygroups/createorupdate#examples

    url = f'https://management.azure.com/subscriptions/{subscription}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}?api-version=2019-09-01'

    data ={
          "properties": {
            "securityRules": [
              {
                "name": "CustomInBound",
                "properties": {
                  "protocol": "*",
                  "sourceAddressPrefix": "*",
                  "destinationAddressPrefix": "*",
                  "access": "Allow",
                  "destinationPortRange": "*",
                  "sourcePortRange": "*",
                  "priority": 100,
                  "direction": "Inbound"
                }
              },
              {
                "name": "CustomOutBound",
                "properties": {
                  "protocol": "*",
                  "sourceAddressPrefix": "*",
                  "destinationAddressPrefix": "*",
                  "access": "Allow",
                  "destinationPortRange": "*",
                  "sourcePortRange": "*",
                  "priority": 100,
                  "direction": "Outbound"
                }
              },
                            
            ]
          },
          "location": location
        }
    
    success = False
    while not success:
        try:
            response = requests.put(url, headers=headers, data=str(data))
            responseData = response.json()
            if not responseData.get('id'):
                print(responseData)
                print(responseData.text)
                print(responseData.headers)
            else:
                networkSecurityGroupId = responseData['id']
                success = True
        except Exception as e:
            print(e)
    return networkSecurityGroupId

如何将现有子网与新创建的NSG关联?是否可以修改此函数,或者我必须创建另一个函数?也许我应该使用Azure CLI,但使用python

在Azure门户上,它是通过this page完成的


Tags: 函数httpscomapiurldatalocationproperties
1条回答
网友
1楼 · 发布于 2024-03-29 09:17:40

要将NSG与现有子网关联,我知道有三种方法

  1. 我看到您使用RESTAPI来创建NSG。因此,您仍然可以使用REST API here来执行此操作,这里有一个示例体:
{
  "properties": {
    "addressSpace": {
      "addressPrefixes": [
        "172.17.0.0/24"
      ]
    },
    "subnets": [
      {
        "name": "default",
        "properties": {
          "addressPrefix": "172.17.0.0/24",
          "networkSecurityGroup": {
            "id": "xxxxxx",
            "location": "eastasia"
            }
        }
      }
    ]
  },
  "location": "eastasia"
}
  1. 您可以使用Azure Python SDK执行此操作:
subscription_id = "xxxxxx"
credential = ServicePrincipalCredentials(
  client_id="xxxxx",
  secret="xxxxx",
  tenant="xxxxx"
)

network_client = NetworkManagementClient(credential, subscription_id)

resource_group_name = "xxxxx"
vnet_name = "xxxxx"
subnet_name = "xxxxx"
sunet_data = {
  "properties": {
    "addressSpace": {
      "addressPrefixes": [
        "172.17.0.0/24"
      ]
    },
    "subnets": [
      {
        "name": "default",
        "properties": {
          "addressPrefix": "172.17.0.0/24",
          "networkSecurityGroup": {
            "id": networkSecurityGroupId ,
            "location": "eastasia"
            }
        }
      }
    ]
  },
  "location": "eastasia"
}

result = network_client.subnets.create_or_update(resource_group_name, vnet_name, subnet_name, subnet_data)

您可以获得有关subnets的SDK的更多详细信息

  1. Azure CLI也可以做到这一点,您只需通过python代码运行CLI命令:
import subprocess

resource_group_name = "xxxxx"
vnet_name = "xxxxx"
subnet_name = "xxxxx"
cmd = f"az network vnet subnet update -g {resource_group_name} -n {subnet_name}  vnet-name {vnet_name}  network-security-group {networkSecurityGroupId} "

command = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
out, err = command.communicate()

你可以选择你想要的一种方式。如果您在函数中添加代码或创建另一个代码,也可以

相关问题 更多 >