36 lines
1.2 KiB
Python
36 lines
1.2 KiB
Python
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) |