通过PyVim / PyVmomi API在主机上启用SSH

时间:2017-06-23 20:30:08

标签: python vsphere vcenter

有没有办法在ESXi主机上启用SSH?我环顾四周但却一无所获。我正在编写一个脚本,需要能够在主机上启用和禁用SSH。

1 个答案:

答案 0 :(得分:1)

是的,有一些方法可以在ESXi主机上启用SSH。

使用Pyvmomi API

from pyVim.connect import SmartConnect, Disconnect
import ssl
import atexit
from pyVmomi import vim


def connect():
    context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    context.verify_mode = ssl.CERT_NONE

    si = SmartConnect(host='0.0.0.0', user='user', pwd='pass', port=443, sslContext=context)
    atexit.register(Disconnect, si)
    content = si.RetrieveContent()
    return content

def get_obj(content, vimtype, name):
    """
    Return an object by name, if name is None the
    first found object is returned
    """
    obj = None
    container = content.viewManager.CreateContainerView(
        content.rootFolder, vimtype, True)
    for c in container.view:
        if name:
            if c.name == name:
                obj = c
                break
        else:
            obj = c
            break

    container.Destroy()
    return obj

content = connect()

host_system = get_obj(content, [vim.HostSystem], 'NAME_OF_HOSTSYSTEM')
service_system = host_system.configManager.serviceSystem
ssh_service = [x for x in service_system.serviceInfo.service if x.key == 'TSM-SSH'][0]
if not ssh_service.running:
   service_system.Start(ssh_service.key)

# Fun, Profit
service_system.Stop(ssh_service.key) # Stop SSH service.

使用Ansible的vmware_host_service_manager模块

- name: Start SSH service setting for an ESXi Host in given Cluster
  vmware_host_service_manager:
    hostname: '{{ vcenter_hostname }}'
    username: '{{ vcenter_username }}'
    password: '{{ vcenter_password }}'
    esxi_hostname: esxi_name
    service_name: TSM-SSH
    state: present