vSphere Automation SDK for Python实战:5个核心API调用示例教你管理虚拟机

【免费下载链接】vsphere-automation-sdk-python Python samples, language bindings, and API reference documentation for vSphere, VMC, and NSX-T using the VMware REST API 【免费下载链接】vsphere-automation-sdk-python 项目地址: https://gitcode.com/gh_mirrors/vs/vsphere-automation-sdk-python

想要自动化管理VMware vSphere环境中的虚拟机吗?😊 vSphere Automation SDK for Python为您提供了完整的解决方案!作为VMware官方推出的Python软件开发工具包,它让开发者能够通过简洁的Python代码轻松管理vCenter、NSX-T和VMware Cloud on AWS环境。本文将为您展示5个实用的核心API调用示例,帮助您快速掌握虚拟机管理的关键技能。

1️⃣ 环境准备与SDK安装

开始之前,您需要准备好Python开发环境并安装vSphere Automation SDK。以下是快速安装指南:

# 克隆项目仓库
git clone https://gitcode.com/gh_mirrors/vs/vsphere-automation-sdk-python

# 安装SDK包
pip install --upgrade pip
pip install vmware-vapi

如果您需要本地安装,可以使用项目中的wheel文件:lib/vsphere-automation-sdk-python/。

2️⃣ 连接vCenter服务器

建立连接是使用SDK的第一步。这里展示两种连接方式:

# 基本连接示例
from vmware.vapi.vsphere.client import create_vsphere_client
import requests
import urllib3

# 创建会话
session = requests.session()
session.verify = False
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# 连接到vCenter
vsphere_client = create_vsphere_client(
    server='your-vcenter-ip',
    username='your-username',
    password='your-password',
    session=session
)

安全提示:生产环境中请使用证书验证,不要禁用SSL验证!

3️⃣ 虚拟机列表查询与管理

获取所有虚拟机信息

查询vCenter中所有虚拟机的状态信息:

# 获取虚拟机列表
vm_list = vsphere_client.vcenter.VM.list()

# 显示虚拟机信息
for vm in vm_list:
    print(f"VM ID: {vm.vm}")
    print(f"名称: {vm.name}")
    print(f"电源状态: {vm.power_state}")
    print(f"CPU核心数: {vm.cpu_count}")
    print(f"内存大小: {vm.memory_size_mib} MB")
    print("-" * 40)

这个API调用返回虚拟机的核心信息,包括ID、名称、电源状态和资源配置等。相关代码可以在samples/vsphere/vcenter/vm/目录中找到。

按条件筛选虚拟机

# 只获取运行中的虚拟机
running_vms = vsphere_client.vcenter.VM.list(
    filter_power_states={'POWERED_ON'}
)

# 获取特定文件夹中的虚拟机
folder_vms = vsphere_client.vcenter.VM.list(
    filter_folders={'folder-id-here'}
)

4️⃣ 虚拟机电源管理操作

启动虚拟机

# 启动虚拟机
def start_virtual_machine(vm_id):
    try:
        vsphere_client.vcenter.VM.power.start(vm_id)
        print(f"虚拟机 {vm_id} 启动成功")
    except Exception as e:
        print(f"启动失败: {str(e)}")

# 使用示例
start_virtual_machine('vm-123')

停止和重启虚拟机

# 停止虚拟机(软关闭)
vsphere_client.vcenter.VM.power.stop('vm-123')

# 强制停止(硬关机)
vsphere_client.vcenter.VM.power.stop('vm-123', force=True)

# 重启虚拟机
vsphere_client.vcenter.VM.power.reset('vm-123')

更多电源管理示例可以参考samples/vsphere/vcenter/vm/power.py

5️⃣ 虚拟机配置修改

修改CPU和内存配置

# 修改虚拟机CPU配置
def update_vm_cpu(vm_id, cpu_count):
    cpu_spec = vsphere_client.vcenter.vm.hardware.Cpu.UpdateSpec(
        count=cpu_count,
        cores_per_socket=2
    )
    vsphere_client.vcenter.vm.hardware.Cpu.update(vm_id, cpu_spec)
    print(f"虚拟机 {vm_id} CPU已更新为 {cpu_count} 核心")

# 修改内存配置
def update_vm_memory(vm_id, memory_mb):
    memory_spec = vsphere_client.vcenter.vm.hardware.Memory.UpdateSpec(
        size_mib=memory_mb
    )
    vsphere_client.vcenter.vm.hardware.Memory.update(vm_id, memory_spec)
    print(f"虚拟机 {vm_id} 内存已更新为 {memory_mb} MB")

添加虚拟磁盘

# 为虚拟机添加新磁盘
def add_virtual_disk(vm_id, size_gb):
    disk_spec = vsphere_client.vcenter.vm.hardware.Disk.CreateSpec(
        new_vmdk=vsphere_client.vcenter.vm.hardware.Disk.VmdkCreateSpec(
            capacity=size_gb * 1024  # 转换为MB
        )
    )
    disk_id = vsphere_client.vcenter.vm.hardware.Disk.create(vm_id, disk_spec)
    print(f"为虚拟机 {vm_id} 添加了 {size_gb}GB 磁盘,磁盘ID: {disk_id}")
    return disk_id

硬件配置的完整示例可以在samples/vsphere/vcenter/vm/hardware/目录中找到。

6️⃣ 虚拟机创建与删除

创建新虚拟机

# 创建基本虚拟机
def create_basic_vm(vm_name, datastore_id, folder_id):
    placement_spec = vsphere_client.vcenter.vm.PlacementSpec(
        folder=folder_id,
        datastore=datastore_id
    )
    
    vm_create_spec = vsphere_client.vcenter.vm.CreateSpec(
        name=vm_name,
        guest_os='WINDOWS_9_64',
        placement=placement_spec
    )
    
    vm_id = vsphere_client.vcenter.VM.create(vm_create_spec)
    print(f"虚拟机 {vm_name} 创建成功,ID: {vm_id}")
    return vm_id

创建虚拟机的更多选项可以参考samples/vsphere/vcenter/vm/create/中的示例。

删除虚拟机

# 删除虚拟机
def delete_virtual_machine(vm_id):
    # 先检查虚拟机状态
    vm_info = vsphere_client.vcenter.VM.get(vm_id)
    
    # 如果虚拟机正在运行,先关闭
    if vm_info.power_state == 'POWERED_ON':
        vsphere_client.vcenter.VM.power.stop(vm_id)
        print(f"虚拟机 {vm_id} 已关闭")
    
    # 删除虚拟机
    vsphere_client.vcenter.VM.delete(vm_id)
    print(f"虚拟机 {vm_id} 删除成功")

7️⃣ 高级功能:标签管理和快照

为虚拟机添加标签

# 创建标签分类
def create_tag_category(category_name):
    category_create_spec = vsphere_client.tagging.Category.CreateSpec(
        name=category_name,
        description="虚拟机环境分类",
        cardinality="SINGLE"
    )
    category_id = vsphere_client.tagging.Category.create(category_create_spec)
    return category_id

# 创建标签并应用到虚拟机
def tag_virtual_machine(vm_id, tag_name, category_id):
    tag_create_spec = vsphere_client.tagging.Tag.CreateSpec(
        name=tag_name,
        description="生产环境虚拟机",
        category_id=category_id
    )
    tag_id = vsphere_client.tagging.Tag.create(tag_create_spec)
    
    # 将标签应用到虚拟机
    vsphere_client.tagging.TagAssociation.attach(
        object_id={'id': vm_id, 'type': 'VirtualMachine'},
        tag_id=tag_id
    )
    print(f"标签 {tag_name} 已应用到虚拟机 {vm_id}")

创建虚拟机快照

# 创建虚拟机快照
def create_vm_snapshot(vm_id, snapshot_name, description=""):
    snapshot_spec = vsphere_client.vcenter.vm.snapshot.CreateSpec(
        name=snapshot_name,
        description=description,
        memory=False  # 是否包含内存状态
    )
    
    snapshot_id = vsphere_client.vcenter.vm.snapshot.create(
        vm=vm_id,
        spec=snapshot_spec
    )
    print(f"快照 {snapshot_name} 创建成功,ID: {snapshot_id}")
    return snapshot_id

🎯 实用技巧与最佳实践

错误处理与重试机制

import time
from vmware.vapi.lib.exceptions import Unauthorized, ServiceUnavailable

def safe_api_call(api_func, *args, max_retries=3, **kwargs):
    """安全的API调用,包含重试机制"""
    for attempt in range(max_retries):
        try:
            return api_func(*args, **kwargs)
        except ServiceUnavailable:
            if attempt < max_retries - 1:
                wait_time = 2 ** attempt  # 指数退避
                print(f"服务暂时不可用,{wait_time}秒后重试...")
                time.sleep(wait_time)
            else:
                raise
        except Unauthorized:
            print("认证失败,请检查凭据")
            raise

性能优化建议

  1. 批量操作:尽量减少API调用次数,使用批量操作
  2. 连接复用:保持会话连接,避免频繁重新认证
  3. 异步处理:对于长时间运行的操作,考虑使用异步方式
  4. 缓存机制:缓存不经常变化的数据,如虚拟机列表

📚 学习资源与下一步

官方文档参考

进阶学习路径

  1. 深入学习:研究samples/vsphere/contentlibrary/中的内容库管理
  2. 网络管理:探索samples/vsphere/vcenter/network/中的网络配置示例
  3. 存储管理:学习samples/vsphere/vcenter/storage/中的存储操作
  4. 监控告警:查看samples/vsphere/appliances/中的监控功能

💡 总结

通过这5个核心API调用示例,您已经掌握了使用vSphere Automation SDK for Python管理虚拟机的基本技能。从环境准备到连接建立,从虚拟机查询到配置修改,再到高级的标签和快照管理,这些示例覆盖了日常运维中最常见的场景。

vSphere Automation SDK的强大之处在于它的完整性和易用性,让Python开发者能够轻松地将vSphere管理集成到自己的自动化工具和脚本中。无论您是运维工程师、开发人员还是系统管理员,掌握这个工具都将大幅提升您的工作效率。

立即开始您的vSphere自动化之旅吧! 🚀 通过实践这些示例,您将能够构建出更加强大和灵活的虚拟化管理解决方案。

【免费下载链接】vsphere-automation-sdk-python Python samples, language bindings, and API reference documentation for vSphere, VMC, and NSX-T using the VMware REST API 【免费下载链接】vsphere-automation-sdk-python 项目地址: https://gitcode.com/gh_mirrors/vs/vsphere-automation-sdk-python

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐