MJonny
MJonny

Reputation: 21

enable SSH on host via PyVim / PyVmomi API

Is there a way to enable SSH on an ESXi host? I have looked around but have found nothing. I am writing a script that needs to be able to enable and disable SSH on a host.

Upvotes: 2

Views: 3467

Answers (1)

Abhijeet Kasurde
Abhijeet Kasurde

Reputation: 4117

Yes, there are ways to enable SSH on an ESXi host.

Using 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.

And using Ansible's vmware_host_service_manager module

- 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

Upvotes: 2

Related Questions