接近完善的代码,待生产环境测试。

This commit is contained in:
panjunlan
2026-02-21 14:26:14 +08:00
parent 9024e9c8e4
commit 17e9e0c3bc
11 changed files with 357 additions and 293 deletions

36
core/vm_connector.py Normal file
View File

@@ -0,0 +1,36 @@
import ssl
from pyVim.connect import SmartConnect, Disconnect
from config.settings import MANAGEMENT_NODES
from utils.logger import logger # 复用你之前的日志配置
def connect_vcenter(host):
"""
根据NodeHost连接对应vCenter/ESXi
:param host: 节点IP/主机名
:return: ServiceInstance对象
:raise: Exception连接失败/未找到配置)
"""
# 遍历全局配置的MANAGEMENT_NODES
for node in MANAGEMENT_NODES:
if node['host'] == host:
context = ssl._create_unverified_context() # 禁用SSL验证
si = SmartConnect(
host=node['host'],
user=node['user'],
pwd=node['password'],
sslContext=context # 规范的SSL配置
)
if not si:
raise Exception(f"{host}连接成功但未返回ServiceInstance")
logger.info(f"成功连接到节点: {host}")
return si
# 匹配不到 host 主动抛异常
logger.error(f"未找到节点 {host} 的连接信息")
raise Exception(f"未找到 {host} 的连接信息")
if __name__ == "__main__":
si = connect_vcenter(MANAGEMENT_NODES[0]['host'])
print(si)