当前位置:   article > 正文

Python实现VMware自动化资源巡检

Python实现VMware自动化资源巡检

推送效果:

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(//)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

python代码:

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

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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/320307?site
推荐阅读
相关标签
  

闽ICP备14008679号