Python实现VMware自动化资源巡检

推送效果:

dart 复制代码
E:\PYPJ1\Scripts\python.exe C:\Users\PycharmProjects\pythonProject\main.py 
自动化巡检-执行时间:2024-03-25 14:47:04
Connected to vCenter
Found datacenter: CN-SH-Datacenter

----------存储资源指标----------
资源总容量:193.93TB
总利用率:59.89%
总已用容量:116.14TB
总空闲容量:77.79TB
健康阈值内总可用容量(<80%):39.40TB
VMware可用容量:14.05TB
NAS可用容量:25.34TB
宿主机存储资源负载分布(台):2/8/8(高/中/低)

----------内存资源指标----------
资源总容量: 8941 GB
总利用率:38.87%
总已用容量: 3475 GB
总空闲容量: 5466 GB
健康阈值内总可用容量(<80%): 3677 GB
宿主机内存资源负载分布(台)0/1/17(高/中/低)

python代码:

注:关于存储我只过滤了以"Data-"开头的存储,因为那个是我的数据存储,其他的都是系统存储可以忽略。

dart 复制代码
from pyVim import connect
from pyVmomi import vim
import ssl
import time
from datetime import datetime, timedelta


# 脚本运行时间
starttime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
start_time = time.time()
print("自动化巡检-执行时间:" + starttime)

# 创建一个不验证SSL证书的上下文
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE

# vCenter Server IP地址或主机名
vc_host = '192.168.1.1'
# vCenter登录凭据(用户名、密码)
username = 'test@vsphere.local'
password = 'qwe123456'
port = 443  # 默认vCenter端口

def calculate_memory_metrics(host):
    summary = host.summary
    memory_usage = summary.quickStats.overallMemoryUsage
    memory_capacity = summary.hardware.memorySize

    # 计算内存使用情况(以GB为单位)
    memory_usage_gb = int(memory_usage / 1024)
    memory_capacity_gb = int(memory_capacity / 1024 / 1024 / 1024)
    memory_free_gb = memory_capacity_gb - memory_usage_gb

    return memory_usage_gb, memory_capacity_gb, memory_free_gb

def get_storage_free_capacity(storage_info, storage_name):
    for storage in storage_info:
        if storage[0] == storage_name:
            return storage[1] - storage[2]
    return None

def process_storage_info(storage_info):
    print()
    print("----------存储资源指标----------")
    # 存储资源总容量
    total_capacity = sum(storage[1] for storage in storage_info)
    # 已用容量
    used_capacity = sum(storage[2] for storage in storage_info)
    # 空闲容量
    free_capacity = total_capacity - used_capacity
    # 利用率
    usage_percentage = (used_capacity / total_capacity) * 100

    # 主机资源分布
    high_usage = [storage for storage in storage_info if storage[3] > 80]
    medium_usage = [storage for storage in storage_info if 60 <= storage[3] <= 80]
    low_usage = [storage for storage in storage_info if storage[3] < 60]
    host_distribution = f"{len(high_usage)}/{len(medium_usage)}/{len(low_usage)}"

    # 可用容量
    available_capacity = sum((storage[1] * 0.8) - storage[2] for storage in storage_info if storage[3] < 80)
    free_capacity_data_25 = get_storage_free_capacity(storage_info, "Data-25")
    free_vmware = available_capacity - free_capacity_data_25

    # 构建输出字符串
    output = f"资源总容量:{total_capacity:.2f}TB\n总利用率:{usage_percentage:.2f}%\n"
    output += f"总已用容量:{used_capacity:.2f}TB\n总空闲容量:{free_capacity:.2f}TB\n"
    output += f"健康阈值内总可用容量(<80%):{available_capacity:.2f}TB\n"
    output += f"VMware可用容量:{free_vmware:.2f}TB\nNAS可用容量:{free_capacity_data_25:.2f}TB\n"
    output += f"宿主机存储资源负载分布(台):{host_distribution}(高/中/低)\n"
    print(output)

def connect_vcenter():
    try:
        # 使用自定义的SSL上下文建立与vCenter服务器的连接
        service_instance = connect.SmartConnect(host=vc_host, user=username, pwd=password, port=port, sslContext=context)
        # 现在可以使用service_instance访问vCenter的内容
        print("Connected to vCenter")
        return service_instance
    except Exception as e:
        print("Failed to connect to the vCenter server:", e)
        return None

def get_storage_info(service_instance):
    storages = []
    content = service_instance.RetrieveContent()

    # 获取所有数据中心
    datacenters = content.rootFolder.childEntity

    for datacenter in datacenters:
        if isinstance(datacenter, vim.Datacenter):
            print("Found datacenter:", datacenter.name)

            # 获取数据中心下的所有存储
            datastores = datacenter.datastore

            for datastore in datastores:
                if isinstance(datastore, vim.Datastore) and datastore.name.startswith("Data-"):
                    # 获取存储容量信息
                    summary = datastore.summary
                    storage_name = datastore.name
                    storage_capacity = summary.capacity / 1024 ** 4
                    storage_used_capacity = (summary.capacity - summary.freeSpace) / 1024 ** 4
                    storage_usage_percentage = ((summary.capacity - summary.freeSpace) / summary.capacity) * 100
                    storages.append((storage_name, storage_capacity, storage_used_capacity, storage_usage_percentage))
    return storages

def disconnect_vcenter(service_instance):
    # 断开与vCenter服务器的连接
    if service_instance:
        connect.Disconnect(service_instance)

def main():
    # 连接vCenter服务器
    service_instance = connect_vcenter()

    if service_instance:
        # 处理存储指标
        storages = get_storage_info(service_instance)
        process_storage_info(storages)

        # 获取vCenter中所有宿主机
        content = service_instance.RetrieveContent()
        container = content.rootFolder
        view_type = [vim.HostSystem]
        recursive = True
        container_view = content.viewManager.CreateContainerView(container, view_type, recursive)

        total_memory = 0
        used_memory = 0
        free_memory = 0
        high_usage_hosts = 0
        medium_usage_hosts = 0
        low_usage_hosts = 0

        # 遍历所有宿主机
        for host in container_view.view:
            memory_usage, memory_capacity, memory_free = calculate_memory_metrics(host)

            # 累计总量、已用和空闲内存
            total_memory += memory_capacity
            used_memory += memory_usage
            free_memory += memory_free

            # 根据内存使用率判断宿主机的负载
            usage_percentage = (memory_usage / memory_capacity) * 100
            if usage_percentage > 80:
                high_usage_hosts += 1
            elif 60 <= usage_percentage <= 80:
                medium_usage_hosts += 1
            else:
                low_usage_hosts += 1

            ## 打印宿主机名称和内存使用情况
            # print("宿主机名称:", host.name)
            # print("已用内存:", memory_usage, "GB")
            # print("总内存容量:", memory_capacity, "GB")
            # print("剩余内存:", memory_free, "GB")
            # print()

        # 计算健康阈值内的总可用容量
        healthy_threshold_capacity = 0
        if total_memory > 0:
            for host in container_view.view:
                memory_usage, memory_capacity, memory_free = calculate_memory_metrics(host)
                usage_percentage = (memory_usage / memory_capacity) * 100
                if usage_percentage < 80:
                    healthy_threshold_capacity += (memory_capacity * 0.8) - memory_usage
                else:
                    healthy_threshold_capacity += 0

        # 打印内存资源指标
        print("----------内存资源指标----------")
        print("资源总容量:", total_memory, "GB")
        print("总利用率:{:.2f}%".format((used_memory / total_memory) * 100))
        print("总已用容量:", used_memory, "GB")
        print("总空闲容量:", free_memory, "GB")
        print("健康阈值内总可用容量(<80%):", int(healthy_threshold_capacity), "GB")
        print("宿主机内存资源负载分布(台){}/{}/{}(高/中/低)".format(high_usage_hosts, medium_usage_hosts, low_usage_hosts))

        # 断开与vCenter服务器的连接
        disconnect_vcenter(service_instance)

if __name__ == "__main__":
    main()
相关推荐
qq_435070782 分钟前
python乱炖6——sum(),指定维度进行求和
pytorch·python·深度学习
weixin_4181235515 分钟前
Selenium点击元素的方法
python·selenium
小胖伦的夕阳粉23 分钟前
js 获取树节点上某节点的最底层叶子节点数据
开发语言·javascript·ecmascript
怒放的生命.26 分钟前
电气自动化入门05:三相异步电动机的正反转点动控制电路
运维·自动化·电气自动化·电工基础
不见长安见晨雾32 分钟前
将Java程序打包成EXE程序
java·开发语言
豌豆花下猫33 分钟前
Python 潮流周刊#70:微软 Excel 中的 Python 正式发布!(摘要)
后端·python·ai
可愛小吉35 分钟前
Python 课程14-TensorFlow
开发语言·人工智能·python·tensorflow
编程零零七36 分钟前
Python数据分析工具(四):pymysql的用法
开发语言·python·oracle·数据挖掘·数据分析·python项目·python源码
六点半88838 分钟前
【C/C++】速通涉及string类的经典编程题
c语言·开发语言·c++·算法
汤姆和杰瑞在瑞士吃糯米粑粑40 分钟前
string类(C++)
开发语言·c++