# Product: vCenter server/vCenter Server High Availability (VCHA)
# Description: Python script to deploy vCenter server HA 
# Reference:http://vthinkbeyondvm.com/how-to-manage-vcenter-server-ha-using-vsphere-python-sdk-pyvmomi-part-1/
# How to setup pyVmomi environment?: http://vthinkbeyondvm.com/how-did-i-get-started-with-the-vsphere-python-sdk-pyvmomi-on-ubuntu-distro/

from pyVim.connect import SmartConnect
from pyVmomi import vim
import ssl
# Deploying vCenter HA in basic mode using self managed VC 

# For VC 6.5/6.0
#s=ssl.SSLContext(ssl.PROTOCOL_TLSv1)
# For VC 6.7
s = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
s.verify_mode=ssl.CERT_NONE
si= SmartConnect(host="10.161.34.35", user="******", pwd="VMware#12",sslContext=s)
content=si.content

#Parameters required are hardcoded below, please do change as per your environment.

vcha_network_name="VCHA" #port group name, I am using standard switch.
vcha_dc_name="IndiaDC"    #Datacenter name 
vcha_subnet_mask="255.255.255.0"  #Subnect mask for vCenter HA/Private network
active_vcha_ip="192.168.0.1"    # Active node vCenter HA IP
passive_vcha_ip="192.168.0.2"   # Passive node vCenter HA IP
witness_vcha_ip="192.168.0.3"   # Witness node vCenter HA IP
active_vcha_vm_name="vThinkBVM-VC1" #Active node/VC VM name
active_vc_username="******"  #Active VC username
active_vc_password="******"  #Active VC password
active_vc_url="https://10.61.34.35"  #Active VC public IP
active_vc_thumbprint="55:A9:C5:7E:0C:CD:46:26:D3:5C:C2:92:B7:0F:A7:91:E5:CD:0D:5D" #Active VC thumbprint
Exemplo n.º 2
0
def main():
    args = GetArgs()
    if args.password:
        password = args.password
    else:
        password = getpass.getpass(prompt='Enter password for host %s and '
                                          'user %s: ' % (args.host, args.user))

# For python 2.7.9 and later, the defaul SSL conext has more strict
# connection handshaking rule. We may need turn off the hostname checking
# and client side cert verification
    context = None
    if sys.version_info[:3] > (2, 7, 8):
        context = ssl.create_default_context()
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE

    si = SmartConnect(host=args.host,
                      user=args.user,
                      pwd=password,
                      port=int(args.port),
                      sslContext=context)

    atexit.register(Disconnect, si)

    # for detecting whether the host is VC or ESXi
    aboutInfo = si.content.about

    if aboutInfo.apiType == 'VirtualCenter':
        majorApiVersion = aboutInfo.apiVersion.split('.')[0]
        if int(majorApiVersion) < 6:
            print('The Virtual Center with version %s (lower than 6.0) is not supported.'
                  % aboutInfo.apiVersion)
            return -1

        # Here is an example of how to access VC side VSAN Health Service API
        vcMos = vsanapiutils.GetVsanVcMos(si._stub, context=context)
        # Get vsan health system
        vhs = vcMos['vsan-cluster-health-system']

        cluster = getClusterInstance(args.clusterName, si)

        if cluster is None:
            print("Cluster %s is not found for %s" %
                  (args.clusterName, args.host))
            return -1
        # VSAN cluster health summary can be cached at VC.
        fetchFromCache = True
        fetchFromCacheAnswer = raw_input(
            'Do you want to fetch the cluster health from cache if exists?(y/n):')
        if fetchFromCacheAnswer.lower() == 'n':
            fetchFromCache = False
        print('Fetching cluster health from cached state: %s' %
              ('Yes' if fetchFromCache else 'No'))
        healthSummary = vhs.QueryClusterHealthSummary(
            cluster=cluster, includeObjUuids=True, fetchFromCache=fetchFromCache)
        clusterStatus = healthSummary.clusterStatus

        print("Cluster %s Status: %s" %
              (args.clusterName, clusterStatus.status))
        for hostStatus in clusterStatus.trackedHostsStatus:
            print("Host %s Status: %s" %
                  (hostStatus.hostname, hostStatus.status))

        # Here is an example of how to track a task retruned by the VSAN API
        vsanTask = vhs.RepairClusterObjectsImmediate(cluster)
        # need covert to vcTask to bind the MO with vc session
        vcTask = vsanapiutils.ConvertVsanTaskToVcTask(vsanTask, si._stub)
        vsanapiutils.WaitForTasks([vcTask], si)
        print('Repairing cluster objects task completed with state: %s'
              % vcTask.info.state)

    if aboutInfo.apiType == 'HostAgent':
        majorApiVersion = aboutInfo.apiVersion.split('.')[0]
        if int(majorApiVersion) < 6:
            print('The ESXi with version %s (lower than 6.0) is not supported.'
                  % aboutInfo.apiVersion)
            return -1
Exemplo n.º 3
0
def _get_service_instance(host, username, password, protocol, port, mechanism,
                          principal, domain):
    '''
    Internal method to authenticate with a vCenter server or ESX/ESXi host
    and return the service instance object.
    '''
    log.trace('Retrieving new service instance')
    token = None
    if mechanism == 'userpass':
        if username is None:
            raise salt.exceptions.CommandExecutionError(
                'Login mechanism userpass was specified but the mandatory '
                'parameter \'username\' is missing')
        if password is None:
            raise salt.exceptions.CommandExecutionError(
                'Login mechanism userpass was specified but the mandatory '
                'parameter \'password\' is missing')
    elif mechanism == 'sspi':
        if principal is not None and domain is not None:
            try:
                token = get_gssapi_token(principal, host, domain)
            except Exception as exc:
                raise salt.exceptions.VMwareConnectionError(str(exc))
        else:
            err_msg = 'Login mechanism \'{0}\' was specified but the' \
                      ' mandatory parameters are missing'.format(mechanism)
            raise salt.exceptions.CommandExecutionError(err_msg)
    else:
        raise salt.exceptions.CommandExecutionError(
            'Unsupported mechanism: \'{0}\''.format(mechanism))
    try:
        log.trace('Connecting using the \'{0}\' mechanism, with username '
                  '\'{1}\''.format(mechanism, username))
        service_instance = SmartConnect(host=host,
                                        user=username,
                                        pwd=password,
                                        protocol=protocol,
                                        port=port,
                                        b64token=token,
                                        mechanism=mechanism)
    except TypeError as exc:
        if 'unexpected keyword argument' in exc.message:
            log.error('Initial connect to the VMware endpoint failed with {0}'.
                      format(exc.message))
            log.error(
                'This may mean that a version of PyVmomi EARLIER than 6.0.0.2016.6 is installed.'
            )
            log.error('We recommend updating to that version or later.')
            raise
    except Exception as exc:

        default_msg = 'Could not connect to host \'{0}\'. ' \
                      'Please check the debug log for more information.'.format(host)

        try:
            if (isinstance(exc, vim.fault.HostConnectFault) and
                '[SSL: CERTIFICATE_VERIFY_FAILED]' in exc.msg) or \
               '[SSL: CERTIFICATE_VERIFY_FAILED]' in str(exc):

                import ssl
                service_instance = SmartConnect(
                    host=host,
                    user=username,
                    pwd=password,
                    protocol=protocol,
                    port=port,
                    sslContext=ssl._create_unverified_context(),
                    b64token=token,
                    mechanism=mechanism)
            else:
                err_msg = exc.msg if hasattr(exc, 'msg') else default_msg
                log.trace(exc)
                raise salt.exceptions.VMwareConnectionError(err_msg)
        except Exception as exc:
            if 'certificate verify failed' in str(exc):
                import ssl
                context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
                context.verify_mode = ssl.CERT_NONE
                try:
                    service_instance = SmartConnect(host=host,
                                                    user=username,
                                                    pwd=password,
                                                    protocol=protocol,
                                                    port=port,
                                                    sslContext=context,
                                                    b64token=token,
                                                    mechanism=mechanism)
                except Exception as exc:
                    err_msg = exc.msg if hasattr(exc, 'msg') else str(exc)
                    log.trace(err_msg)
                    raise salt.exceptions.VMwareConnectionError(
                        'Could not connect to host \'{0}\': '
                        '{1}'.format(host, err_msg))
            else:
                err_msg = exc.msg if hasattr(exc, 'msg') else default_msg
                log.trace(exc)
                raise salt.exceptions.VMwareConnectionError(err_msg)
    atexit.register(Disconnect, service_instance)
    return service_instance
Exemplo n.º 4
0
from tools import cli

PARSER = cli.build_arg_parser()
# If you are unsure where to get the UUID of your HostSystem check out the
# MOB. For example in my lab I would connect directly to the host mob like so:
# https://10.12.254.10/mob/?moid=ha-host&doPath=hardware%2esystemInfo
PARSER.add_argument("-x",
                    "--uuid",
                    required=True,
                    action="store",
                    help="The UUID of the HostSystem to list triggered alarms"
                    " for.")
MY_ARGS = PARSER.parse_args()
cli.prompt_for_password(MY_ARGS)
SI = SmartConnect(host=MY_ARGS.host,
                  user=MY_ARGS.user,
                  pwd=MY_ARGS.password,
                  port=MY_ARGS.port)

atexit.register(Disconnect, SI)
INDEX = SI.content.searchIndex
if INDEX:
    HOST = INDEX.FindByUuid(datacenter=None, uuid=MY_ARGS.uuid, vmSearch=False)
    alarm.print_triggered_alarms(entity=HOST)
    # Since the above method will list all of the triggered alarms we will now
    # prompt the user for the entity info needed to reset an alarm from red
    # to green
    try:
        alarm_mor = raw_input("Enter the alarm_moref from above to reset the "
                              "alarm to green: ")
    except KeyboardInterrupt:
        # this is useful in case the user decides to quit and hits control-c