Files
RemoveWeeklyShapshot/vcenter_connector.py
2026-02-18 11:41:03 +08:00

40 lines
1.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim
from config.settings import VCENTER_USER, VCENTER_PASSWORD
from utils.logger import logger
def connect_to_vcenter(vcenter_host):
"""
连接到指定的vCenter服务器
:param vcenter_host: vCenter主机名/IP
:return: 成功返回ServiceInstance失败返回None
"""
try:
# 禁用SSL证书验证生产环境建议启用证书验证
si = SmartConnect(
host=vcenter_host,
user=VCENTER_USER,
pwd=VCENTER_PASSWORD,
disableSslCertValidation=True
)
if not si:
logger.error(f"❌ 无法连接到vCenter: {vcenter_host}(无返回实例)")
return None
logger.info(f"✅ 成功连接到vCenter: {vcenter_host}")
return si
except Exception as e:
logger.error(f"❌ 连接vCenter {vcenter_host} 失败: {str(e)}")
return None
def disconnect_from_vcenter(si):
"""
关闭vCenter连接
:param si: ServiceInstance实例
"""
if si:
Disconnect(si)
logger.debug("已关闭vCenter连接")