openstack neutronclient接口学习

Neutron API 实战
本文介绍如何使用 Python 实例化 Neutron 客户端,并通过 Neutron API 进行网络资源的操作,包括创建、更新、删除网络及子网等。

实例化neutronclient

from os import environ as env

# 方式一
from neutronclient.v2_0 import client
neutron = client.Client(username=os.environ['OS_USERNAME']
                        password=os.environ['OS_PASSWORD']
                        auth_url=os.environ['OS_AUTH_URL']
                        tenant_name=os.environ['OS_TENANT_NAME'])

# 方式二
from neutronclient.neutron import client as client
neutron = client.Client('2.0', 
                        username=os.environ['OS_USERNAME']
                        password=os.environ['OS_PASSWORD']
                        auth_url=os.environ['OS_AUTH_URL']
                        tenant_name=os.environ['OS_TENANT_NAME'])

api调用实例

neutron中有一下几种objects:

  • network
  • subnet
  • port
  • router
  • floatingip
  • security_group
  • vpnservices
  • 等等

所有的objects都具有的动作包含:

  • show
    • 查看详情
  • list
    • 查看全部
  • create
    • 新建
  • update
    • 更新

获取所有network信息

# 获取所有network实例
networks = neutron.list_networks()
"""
{
    'networks': [
        {
            u'admin_state_up': True,
            u'id': u'd6e83c1b-1b16-470d-8006-18ee19f6dafe',
            u'mtu': 0,
            u'name': u'ext-net',
            u'provider:network_type': u'flat',
            u'provider:physical_network': u'external',
            u'provider:segmentation_id': None,
            u'router:external': True,
            u'shared': True,
            u'status': u'ACTIVE',
            u'subnets': [u'3ee3f602-86cc-44e9-8fd3-1ecd454760da'],
            u'tenant_id': u'65f273a79a834498a87f3c51bd35bebf'
        },
        {
            u'admin_state_up': True,
            u'id': u'd6e83c1b-1b16-470d-8006-18ee19f6dafe',
            u'mtu': 0,
            u'name': u'ext-net',
            u'provider:network_type': u'flat',
            u'provider:physical_network': u'external',
            u'provider:segmentation_id': None,
            u'router:external': True,
            u'shared': True,
            u'status': u'ACTIVE',
            u'subnets': [u'3ee3f602-86cc-44e9-8fd3-1ecd454760da'],
            u'tenant_id': u'65f273a79a834498a87f3c51bd35bebf'
        },
    ]
}
"""

# 依据条件过滤,条件是返回结果中network实例的属性
# 例如,依据provider:physical_network属性来过滤所有可以通外网的network
filters = {}
filters["provider:physical_network"] = "external"
networks = neutron.list_networks(**filters)

创建network

body_data = {
    'network': {
        "name": "test_creating_network",
        "admin_state_up": True
        "router:external": True,
        "provider:physical_network": "external",
        "provider:network_type": "flat",
    }
}

netw = neutron.create_network(body=body_data)
"""
{
    "network": {
        "status": "ACTIVE",
        "subnets": [],
        "name": "net1",
        "admin_state_up": true,
        "tenant_id": "9bacb3c5d39d41a79512987f338cf177",
        "router:external": True,
        "provider:physical_network": "external",
        "provider:network_type": "flat",
        "segments": [
            {
                "provider:segmentation_id": 2,
                "provider:physical_network": "8bab8453-1bc9-45af-8c70-f83aa9b50453",
                "provider:network_type": "vlan"
            },
            {
                "provider:segmentation_id": null,
                "provider:physical_network": "8bab8453-1bc9-45af-8c70-f83aa9b50453",
                "provider:network_type": "stt"
            }
        ],
        "shared": false,
        "id": "4e8e5957-649f-477b-9e5b-f1f75b21c03c"
    }
}
"""

删除network

body_data = {
    'network': {
        "name": "test_creating_network",
        "admin_state_up": True
        "router:external": True,
        "provider:physical_network": "external",
        "provider:network_type": "flat",
    }
}

netw = neutron.create_network(body=body_data)
net_dict = netw['network']
network_id = net_dict['id']
neutron.delete_network(network_id)

更新network

body_data = {
    'network': {
        "name": "test_creating_network_renew",
    }
}

netw = neutron.update_network(network_id, body=body_data)

查看所有的subnet

subnets = neutron.list_subnets()
"""
{
    "subnets": [
        {
            "name": "private-subnet",
            "enable_dhcp": true,
            "network_id": "db193ab3-96e3-4cb3-8fc5-05f4296d0324",
            "tenant_id": "26a7980765d0414dbc1fc1f88cdb7e6e",
            "dns_nameservers": [],
            "allocation_pools": [
                {
                    "start": "10.0.0.2",
                    "end": "10.0.0.254"
                }
            ],
            "host_routes": [],
            "ip_version": 4,
            "gateway_ip": "10.0.0.1",
            "cidr": "10.0.0.0/24",
            "id": "08eae331-0402-425a-923c-34f7cfe39c1b"
        },
        {
            "name": "my_subnet",
            "enable_dhcp": true,
            "network_id": "d32019d3-bc6e-4319-9c1d-6722fc136a22",
            "tenant_id": "4fd44f30292945e481c7b8a0c8908869",
            "dns_nameservers": [],
            "allocation_pools": [
                {
                    "start": "192.0.0.2",
                    "end": "192.255.255.254"
                }
            ],
            "host_routes": [],
            "ip_version": 4,
            "gateway_ip": "192.0.0.1",
            "cidr": "192.0.0.0/8",
            "id": "54d6f61d-db07-451c-9ab3-b9609b6b6f0b"
        }
    ]
}
"""

创建subnet

start = '192.168.199.2'
end = '192.168.199.254'
allocation_pools = {'start': start, 'end': end}
gateway_ip = '192.168.199.1'

body_data = {
    'subnets':{
        'network_id': network_id,
        'cidr': '192.168.199.0/24',
        'ip_version': 4,
        "enable_dhcp": False,
        "allocation_pools": allocation_pools,
        "gateway_ip": gateway_ip,
    }
}

updated = neutron.update_subnet(subnet_id, body=body_data)

ret = neutron.create_subnet(body=body_data)
"""
{
    "subnet": {
        "name": "",
        "enable_dhcp": false,
        "network_id": "d32019d3-bc6e-4319-9c1d-6722fc136a22",
        "tenant_id": "4fd44f30292945e481c7b8a0c8908869",
        "dns_nameservers": [],
        "allocation_pools": [
            {
                "start": "192.168.199.2",
                "end": "192.168.199.254"
            }
        ],
        "host_routes": [],
        "ip_version": 4,
        "gateway_ip": "192.168.199.1",
        "cidr": "192.168.199.0/24",
        "id": "3b80198d-4f7b-4f77-9ef5-774d54e17126"
    }
}
"""

查看所有的port

neutron.list_port()
"""
{
    "ports": [
        {
            "status": "ACTIVE",
            "name": "",
            "allowed_address_pairs": [],
            "admin_state_up": true,
            "network_id": "70c1db1f-b701-45bd-96e0-a313ee3430b3",
            "tenant_id": "",
            "extra_dhcp_opts": [],
            "device_owner": "network:router_gateway",
            "mac_address": "fa:16:3e:58:42:ed",
            "fixed_ips": [
                {
                    "subnet_id": "008ba151-0b8c-4a67-98b5-0d2b87666062",
                    "ip_address": "172.24.4.2"
                }
            ],
            "id": "d80b1a3b-4fc1-49f3-952e-1e2ab7081d8b",
            "security_groups": [],
            "device_id": "9ae135f4-b6e0-4dad-9e91-3c223e385824"
        },
        {
            "status": "ACTIVE",
            "name": "",
            "allowed_address_pairs": [],
            "admin_state_up": true,
            "network_id": "f27aa545-cbdd-4907-b0c6-c9e8b039dcc2",
            "tenant_id": "d397de8a63f341818f198abb0966f6f3",
            "extra_dhcp_opts": [],
            "device_owner": "network:router_interface",
            "mac_address": "fa:16:3e:bb:3c:e4",
            "fixed_ips": [
                {
                    "subnet_id": "288bf4a1-51ba-43b6-9d0a-520e9005db17",
                    "ip_address": "10.0.0.1"
                }
            ],
            "id": "f71a6703-d6de-4be1-a91a-a570ede1d159",
            "security_groups": [],
            "device_id": "9ae135f4-b6e0-4dad-9e91-3c223e385824"
        }
    ]
}
"""

转载于:https://my.oschina.net/alazyer/blog/737942

### OpenStack 中 NIC 接口的配置与使用 在 OpenStack 环境中,NIC(Network Interface Card)接口通常用于定义虚拟机实例如何连接到不同的网络。以下是关于 OpenStack 中 NIC 接口的相关信息及其配置方法。 #### 1. 创建网络服务 API 端点 在网络环境中,首先需要确保已正确设置 OpenStack Neutron 的网络服务 API 端点。这可以通过以下命令完成: ```bash openstack endpoint create --region RegionOne network public http://controller:9696 openstack endpoint create --region RegionOne network internal http://controller:9696 openstack endpoint create --region RegionOne network admin http://controller:9696 ``` 这些命令会为 `network` 服务创建公共、内部和管理端点[^1]。 #### 2. 安装必要的网络组件 为了支持 NIC 配置,在控制器节点上需安装以下软件包: ```bash yum install openstack-neutron openstack-neutron-ml2 \ openstack-neutron-linuxbridge ebtables -y ``` 上述命令将安装核心网络组件以及 Linux Bridge 和 ML2 插件的支持工具。 #### 3. 配置 NIC 接口OpenStack 中,通过 Neutron 提供的功能来管理和分配虚拟网卡给实例。具体操作包括以下几个方面: ##### a. 创建网络 要为实例提供可用的网络资源,先创建一个外部或内部网络: ```bash neutron net-create external_network --shared --router:external=True neutron subnet-create external_network --name=ext_subnet --gateway=<GATEWAY_IP> <NETWORK_CIDR> ``` 这里 `<GATEWAY_IP>` 是网关地址,而 `<NETWORK_CIDR>` 表示子网范围。 ##### b. 添加路由器 为了让不同子网之间通信顺畅,还需要创建并关联路由器至所建网络: ```bash neutron router-create demo_router neutron router-interface-add demo_router <SUBNET_ID> neutron router-gateway-set demo_router external_network ``` 此过程设置了默认路由路径以便流量能够进出云环境内外部区域。 ##### c. 实例绑定多张网卡 (Port) 当部署新 VM 时,默认情况下只会附加一张主网卡;如果希望增加额外适配器,则可通过指定参数实现自定义行为: ```json { "server": { ... "networks": [ {"uuid": "<PRIVATE_NETWORK_UUID>"}, {"port": "<ADDITIONAL_PORT_ID>"} ] } } ``` 以上 JSON 数据结构展示了如何向 Nova 请求提交包含多个网络选项的新服务器请求。其中 `"uuid"` 对应于现有私有网络 ID ,而 `"port"` 则指向预先准备好的独立端口号。 #### 4. 解决常见问题 有时可能会遇到因缺少必要密钥而导致虚拟机无法启动的情况,例如错误提示:“Secret not found”。此时应该核查 Libvirt 是否正确定义了存储密码所需的 UUID 值,并重新同步数据库记录以匹配实际硬件状态[^3]。 --- ### 示例代码片段 下面是一个简单的 Python 脚本例子,展示如何利用 OpenStack SDK 动态获取当前租户下的所有端口详情列表: ```python from openstack import connection conn = connection.Connection(auth_url="http://<CONTROLLER>:5000/v3", project_name="<PROJECT_NAME>", username="<USERNAME>", password="<PASSWORD>", user_domain_id='default', project_domain_id='default') ports = conn.network.ports() for port in ports: print(f"Port Name: {port.name} | Status: {port.status}") ``` 该脚本能帮助管理员快速定位哪些设备正在占用特定 IP 地址段或者检查连通性状况等问题。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值