Python实现VMware自动化资源巡检
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()