Python:批量开启vCenter Server中ESXi主机的SSH服务

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author         : Xiong Wen Wei
# @Email          : 184859498@qq.com
# @Time           : 3/26/2021 19:04
# @Version        : 1.0
# @File           : enable_esxi_ssh.py
# @Software       : PyCharm

import time
from pyVim import connect
import ssl
import atexit
from pyVmomi import vim

from pyVim.connect import SmartConnect, Disconnect, SmartConnectNoSSL
import humanize
from datetime import datetime


def get_obj(content, vimtype):
    """
    Return an object by view
    """
    container = content.viewManager.CreateContainerView(
        content.rootFolder, vimtype, True)
    obj = container.view
    container.Destroy()
    return obj


#  Start service
def set_services(host_system):
    service_system = host_system.configManager.serviceSystem
    # find SSH service
    ssh_service = [x for x in service_system.serviceInfo.service if x.key == 'TSM-SSH'][0]
    if not ssh_service.running:
        print('Starting SSH ...')
        service_system.Start(ssh_service.key)
        # start and shutdown with host,default is off
        service_system.UpdateServicePolicy(id=ssh_service.key, policy='on')
        print('successfully...')
    else:
        print('Already Started ...')

    return ssh_service


if __name__ == '__main__':
    s = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
    s.verify_mode = ssl.CERT_NONE
    s = ssl._create_unverified_context()
    si = SmartConnect(
        host="vCenter Serve IP地址",
        user="administrator@vsphere.local",
        pwd="密码",
        port=443,
        sslContext=s)
    atexit.register(Disconnect, si)
    content = si.RetrieveContent()

    esxi_num = 0
    host_system_list = get_obj(content, [vim.HostSystem])
    for host_system in host_system_list:
        if host_system.name == '192.168.100.178':
            continue
        print('========> {}'.format(host_system.name))
        set_services(host_system)
        esxi_num += 1
    print(esxi_num)

点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注