python脚本-整理vsphere虚拟机资源/批量开关机虚拟主机

发布于:2024-05-11 ⋅ 阅读:(81) ⋅ 点赞:(0)

1.整理vsphere中的虚拟机资源
将每一台虚拟主机所属esxi主机,虚拟机电源状态,虚拟主机ip,虚拟机的操作系统,虚拟所属文件夹,虚拟机的备注一一对应,存放到xlsx表格。
其中vsphere的目录为:
在这里插入图片描述

from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim
from openpyxl import Workbook
import ssl

def connect_to_vcenter(host, user, pwd):
    try:
        # Disable SSL certificate verification
        ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS)
        ssl_context.verify_mode = ssl.CERT_NONE

        # Connect to vCenter server
        service_instance = SmartConnect(host=host, user=user, pwd=pwd, sslContext=ssl_context)

        return service_instance
    except Exception as e:
        print(f"Error connecting to vCenter: {str(e)}")
        return None

def disconnect_from_vcenter(service_instance):
    try:
        if service_instance:
            Disconnect(service_instance)
    except Exception as e:
        print(f"Error disconnecting from vCenter: {str(e)}")

def get_vm_info(service_instance):
    vm_info = []
    content = service_instance.RetrieveContent()
    container = content.rootFolder  # Root folder for searching
    viewType = [vim.VirtualMachine]  # Type of object to search for
    recursive = True  # Search recursively
    containerView = content.viewManager.CreateContainerView(container, viewType, recursive)

    for vm in containerView.view:
        vm_object = {
            "虚拟机名": vm.name,
            "所属ESXi主机": vm.runtime.host.name,
            "虚拟机电源状态": vm.runtime.powerState,
            "虚拟机IP": vm.guest.ipAddress,
            "虚拟机操作系统": vm.summary.config.guestFullName,
            "虚拟机所属文件夹": vm.parent.name,
            "虚拟机备注": vm.config.annotation
        }
        vm_info.append(vm_object)

    containerView.Destroy()
    return vm_info

def export_to_excel(vm_info, file_path):
    wb = Workbook()
    ws = wb.active
    ws.append(["虚拟机名", "所属ESXi主机", "虚拟机电源状态", "虚拟机IP", "虚拟机操作系统", "虚拟机所属文件夹", "虚拟机备注"])

    for vm in vm_info:
        ws.append([vm["虚拟机名"], vm["所属ESXi主机"], vm["虚拟机电源状态"], vm["虚拟机IP"], vm["虚拟机操作系统"], vm["虚拟机所属文件夹"], vm["虚拟机备注"]])

    wb.save(file_path)
    print(f"虚拟机信息已导出到 {file_path}")

if __name__ == "__main__":
    vcenter_host = "192.168.x.x"  #也可以是域名。比如:vcsa.test.com.cn
    vcenter_user = "test@vsphere.local"
    vcenter_pwd = "Ttttttt123_"
    output_file = "C:\\Users\\111\\Desktop\\rules\\虚拟机信息.xlsx" #存放路径

    # Connect to vCenter
    service_instance = connect_to_vcenter(vcenter_host, vcenter_user, vcenter_pwd)
    if service_instance:
        # Get VM information
        vm_info = get_vm_info(service_instance)
        # Export to Excel
        export_to_excel(vm_info, output_file)

        # Disconnect from vCenter
        disconnect_from_vcenter(service_instance)
    else:
        print("Failed to connect to vCenter.")

运行后的结果:
在这里插入图片描述

2.批量开关机虚拟主机
当需要批量去开关某个项目的虚拟机时,可以有一定的作用。可以优化的地方,将虚拟机名放到一个文本文件中

# 定义要操作的虚拟机名称列表
vm_names = ["test-99.23", "test-99.20"]

# 连接到 vCenter
# 在 Python 中需要使用适当的库来连接到 vCenter,这里假设使用 pyvmomi 库
from pyVim import connect
from pyVmomi import vim
import ssl

# 忽略 SSL 证书验证错误
ssl._create_default_https_context = ssl._create_unverified_context
# 连接到 vCenter
def connect_to_vcenter(host, user, password):
    try:
        service_instance = connect.SmartConnect(host=host, user=user, pwd=password)
        return service_instance
    except Exception as e:
        print("无法连接到vCenter:", str(e))
        return None

# 主程序
def main():
    vcenter_host = "192.168.x.x" #也可以是一个域名
    vcenter_user = "test@vsphere.local"
    vcenter_password = "test"

    service_instance = connect_to_vcenter(vcenter_host, vcenter_user, vcenter_password)
    if not service_instance:
        return

    # 显示菜单以供用户选择操作
    print("请选择要执行的操作:")
    print("0. 关机")
    print("1. 开机")
    print("2. 重启") 

    # 获取用户选择的操作
    choice = input("请输入选项的编号: ")

    # 根据用户选择执行相应的操作
    if choice in ["0", "1", "2"]:
        # 对每个虚拟机执行相同的操作
        for vm_name in vm_names:
            try:
                vm = None
                container = service_instance.content.rootFolder
                viewType = [vim.VirtualMachine]
                recursive = True
                containerView = service_instance.content.viewManager.CreateContainerView(container, viewType, recursive)
                for managedEntity in containerView.view:
                    if managedEntity.name == vm_name:
                        vm = managedEntity
                        break
                if vm:
                    if choice == "0":
                        if vm.runtime.powerState == vim.VirtualMachinePowerState.poweredOn:
                            vm.PowerOff()
                            print(f"虚拟机 {vm_name} 已关机。")
                        else:
                            print(f"虚拟机 {vm_name} 已经是关机状态。")
                    elif choice == "1":
                        if vm.runtime.powerState == "poweredOff":
                            vm.PowerOn()
                            print(f"虚拟机 {vm_name} 已开机。")
                        else:
                            print(f"虚拟机 {vm_name} 已经是开机状态。")
                    elif choice == "2":
                        vm.Reset()
                        print(f"虚拟机 {vm_name} 已重启。")
                else:
                    print(f"无法找到虚拟机 {vm_name}")
            except Exception as e:
                print(f"无法执行操作 {choice} 对虚拟机 {vm_name}: {str(e)}")
    else:
        print("无效的选项,请重新运行脚本并输入正确的选项编号。")

    # 断开与 vCenter 主机的连接
    connect.Disconnect(service_instance)

if __name__ == "__main__":
    main()



网站公告

今日签到

点亮在社区的每一天
去签到