コード例 #1
0
def start_csproot_session():
    session = vspk.NUVSDSession(username=args.cspuser,
                                password=args.passwd,
                                enterprise=args.org,
                                api_url="https://%s:8443" % args.vsd_ip)
    try:
        session.start()
    except:
        logging.error('Failed to start the session')
    return session
コード例 #2
0
def start_csproot_session():
    session = vspk.NUVSDSession(username=username,
                                password=password,
                                enterprise=enterprise,
                                api_url=api_url)
    try:
        session.start()
    except:
        logging.error('Failed to start the session')
    return session.user
コード例 #3
0
 def set_up_connections(self):
     auth = identity.Password(**self.cfg.get_keystone_creds())
     sess = session.Session(auth=auth)
     self.neutron = neutron_client.Client(session=sess)
     self.keystone = keystone_client.Client(session=sess)
     # Set up connection to the VSD
     vsd_session = vspk.NUVSDSession(**self.cfg.get_vsd_creds())
     vsd_session.start()
     self.vsd_user = vsd_session.user
     self.mysql_con = mdb.connect(self.cfg.get_value('db_neutron', 'db_hostname'),
                                  self.cfg.get_value('db_neutron', 'db_username'),
                                  self.cfg.get_value('db_neutron', 'db_password'),
                                  self.cfg.get_value('db_neutron', 'db_name'))
コード例 #4
0
    def __init__(self, config):
        self.cfg = config
        self.logger = logging.getLogger('nuage-neutron-sync')

        auth = identity.Password(**self.cfg.get_keystone_creds())
        sess = session.Session(auth=auth)
        self.neutron = neutron_client.Client(session=sess)
        self.keystone = keystone_client.Client(session=sess)
        self.nova = nova_client.Client(2, session=sess)

        # Set up connection to the VSD
        vsd_session = vspk.NUVSDSession(**self.cfg.get_vsd_creds())
        vsd_session.start()
        self.vsd_user = vsd_session.user
コード例 #5
0
 def connect_vspk(self):
     """
     Connects to a Nuage API endpoint
     """
     try:
         # Connecting to Nuage
         self.nuage_connection = vsdk.NUVSDSession(
             username=self.api_username,
             password=self.api_password,
             enterprise=self.api_enterprise,
             api_url=self.api_url)
         self.nuage_connection.start()
     except BambouHTTPError, e:
         self.module.fail_json(
             msg=
             'Unable to connect to the API URL with given username, password and enterprise: {0}'
             .format(e))
コード例 #6
0
def main():
    """
    Manage the vCenter Integration Node configuration
    """

    # Handling arguments
    args = get_args()
    all_clusters = args.all_clusters
    all_datacenters = args.all_datacenters
    all_hosts = args.all_hosts
    clusters = []
    if args.clusters:
        clusters = args.clusters
    debug = args.debug
    allow_fqdn = args.allow_fqdn
    datacenters = []
    if args.datacenters:
        datacenters = args.datacenters
    hosts = []
    if args.hosts:
        hosts = args.hosts
    host_configure_agent = args.host_configure_agent
    hosts_file = None
    if args.hosts_file:
        hosts_file = args.hosts_file
    hv_username = None
    if args.hv_username:
        hv_username = args.hv_username
    hv_password = None
    if args.hv_password:
        hv_password = args.hv_password
    hv_management_network = None
    if args.hv_management_network:
        hv_management_network = args.hv_management_network
    hv_data_network = None
    if args.hv_data_network:
        hv_data_network = args.hv_data_network
    hv_vm_network = None
    if args.hv_vm_network:
        hv_vm_network = args.hv_vm_network
    hv_mc_network = None
    if args.hv_mc_network:
        hv_mc_network = args.hv_mc_network
    log_file = None
    if args.logfile:
        log_file = args.logfile
    nuage_enterprise = args.nuage_enterprise
    nuage_host = args.nuage_host
    nuage_port = args.nuage_port
    nuage_password = None
    if args.nuage_password:
        nuage_password = args.nuage_password
    nuage_username = args.nuage_username
    nuage_vrs_ovf = None
    if args.nuage_vrs_ovf:
        nuage_vrs_ovf = args.nuage_vrs_ovf
    nosslcheck = args.nosslcheck
    verbose = args.verbose
    vcenter_host = args.vcenter_host
    vcenter_name = vcenter_host
    if args.vcenter_name:
        vcenter_name = args.vcenter_name
    vcenter_https_port = args.vcenter_https_port
    vcenter_http_port = args.vcenter_http_port
    vcenter_password = None
    if args.vcenter_password:
        vcenter_password = args.vcenter_password
    vcenter_username = args.vcenter_username

    # Logging settings
    if debug:
        log_level = logging.DEBUG
    elif verbose:
        log_level = logging.INFO
    else:
        log_level = logging.WARNING

    logging.basicConfig(filename=log_file, format='%(asctime)s %(levelname)s %(message)s', level=log_level)
    logger = logging.getLogger(__name__)

    # Input checking
    if not all_datacenters and len(datacenters) < 1:
        logger.critical('Not all datacenters have to be present in the Nuage Deployment tool (--all-datacenters option NOT enabled), but also no datacenters specified (at least one --datacenter)')
        return 1
    if not all_clusters and len(clusters) < 1:
        logger.critical('Not all clusters have to be present in the Nuage Deployment tool (--all-clusters option NOT enabled), but also no clusters specified (at least one --cluster)')
        return 1
    if not all_hosts and len(hosts) < 1 and not hosts_file:
        logger.critical('Not all hosts have to be present in the Nuage Deployment tool (--all-hosts option NOT enabled), but also no hosts specified (at least one --host or specify a file with the host information via --hosts-file)')
        return 1
    if all_datacenters and len(datacenters) > 0:
        logger.warning('You enabled all datacenters and added individual datacenter options, --all-datacenters takes precendence and overwrites the specified datacenters.')
        datacenters = []
    if all_clusters and len(clusters) > 0:
        logger.warning('You enabled all clusters and added individual cluster options, --all-clusters takes precendence and overwrites the specified clusters.')
        clusters = []
    if all_hosts and len(hosts) > 0 and not hosts_file:
        logger.warning('You enabled all hosts and added individual hosts options, --all-hosts takes precendence and overwrites the specified hosts.')
        hosts = []
    elif all_hosts and len(hosts) < 1 and hosts_file:
        logger.warning('You enabled all hosts and provided a hosts file, the hosts file takes precendence over the --all-hosts flag and this flag will be ignored.')
        all_hosts = False
    elif not all_hosts and len(hosts) > 0 and hosts_file:
        logger.warning('You specified host with the --host argument and provided a hosts file, the hosts file takes precendence over the --host paramerters and these will be ignored.')
        hosts = []

    # CSV Handling
    hosts_list = None
    if hosts_file:
        hosts_list = {}
        # CSV fields:
        # VM Name, Resource Pool, Folder, MAC Address, Post Script
        logger.debug('Parsing csv %s' % hosts_file)

        if not os.path.isfile(hosts_file):
            logger.critical('CSV file %s does not exist, exiting' % hosts_file)
            return 1

        with open(hosts_file, 'rb') as hostlist:
            hosts_list_raw = csv.reader(hostlist, delimiter=',', quotechar='"')
            for row in hosts_list_raw:
                logger.debug('Found CSV row: %s' % ','.join(row))
                # Adding IP to the hosts variable so it can also be used in further handling if it's a valid IP
                if allow_fqdn or ip_address_is_valid(row[0]):
                    hosts_list[row[0]] = row
                    hosts.append(row[0])
                else:
                    logger.warning('Found an invalid IP %s in the hosts file and FQDNs are not allowed, skipping line' % row[0])

    # Disabling SSL verification if set
    ssl_context = None
    if nosslcheck:
        logger.debug('Disabling SSL certificate verification.')
        requests.packages.urllib3.disable_warnings()
        import ssl
        if hasattr(ssl, 'SSLContext'):
            ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
            ssl_context.verify_mode = ssl.CERT_NONE

    # Getting user password for Nuage connection
    if nuage_password is None:
        logger.debug('No command line Nuage password received, requesting Nuage password from user')
        nuage_password = getpass.getpass(prompt='Enter password for Nuage host %s for user %s: ' % (nuage_host, nuage_username))

    # Getting user password for vCenter connection
    if vcenter_password is None:
        logger.debug('No command line vCenter password received, requesting vCenter password from user')
        vcenter_password = getpass.getpass(prompt='Enter password for vCenter host %s for user %s: ' % (vcenter_host, vcenter_username))

    # Getting user password for hosts
    if hv_password is None:
        logger.debug('No command line Host password received, requesting Host password from user')
        hv_password = getpass.getpass(prompt='Enter password for the hosts inside vCenter %s for user %s: ' % (vcenter_host, hv_username))

    try:
        vc = None
        nc = None

        # Connecting to Nuage
        try:
            logger.info('Connecting to Nuage server %s:%s with username %s' % (nuage_host, nuage_port, nuage_username))
            nc = vsdk.NUVSDSession(username=nuage_username, password=nuage_password, enterprise=nuage_enterprise, api_url="https://%s:%s" % (nuage_host, nuage_port))
            nc.start()
        except IOError, e:
            pass

        if not nc or not nc.is_current_session():
            logger.error('Could not connect to Nuage host %s with user %s and specified password' % (nuage_host, nuage_username))
            return 1

        # Connecting to vCenter
        try:
            logger.info('Connecting to vCenter server %s:%s with username %s' % (vcenter_host, vcenter_https_port, vcenter_username))
            if ssl_context:
                vc = SmartConnect(host=vcenter_host, user=vcenter_username, pwd=vcenter_password, port=int(vcenter_https_port), sslContext=ssl_context)
            else:
                vc = SmartConnect(host=vcenter_host, user=vcenter_username, pwd=vcenter_password, port=int(vcenter_https_port))

        except IOError, e:
            pass
コード例 #7
0
# -*- coding: utf-8 -*-
"""
A simple script that will print out a tree structure for each enterprise the user has access to.

--- Usage ---
python list_enterprises_domains_vms_structure_acls.py

--- Author ---
Philippe Dellaert <*****@*****.**>
"""
from vspk import v4_0 as vsdk

session = vsdk.NUVSDSession(username='******',
                            password='******',
                            enterprise='csp',
                            api_url='https://VSD-IP:8443')

session.start()

user = session.user

for cur_ent in user.enterprises.get():
    print('VMs inside Enterprise %s' % cur_ent.name)
    for cur_vm in cur_ent.vms.get():
        print('|- %s' % cur_vm.name)

    print('\nDomains inside Enterprise %s' % cur_ent.name)
    for cur_domain in cur_ent.domains.get():
        print('|- Domain: %s' % cur_domain.name)
        for cur_zone in cur_domain.zones.get():
            print('    |- Zone: %s' % cur_zone.name)
コード例 #8
0
def main():
    """
    Main function to handle vcenter vm os and the mapping to a policy group
    """

    # Handling arguments
    args = get_args()
    clusters = []
    if args.clusters:
        clusters = args.clusters
    debug = args.debug
    log_file = None
    if args.logfile:
        log_file = args.logfile
    mapping_file = args.mapping_file
    nuage_enterprise = args.nuage_enterprise
    nuage_host = args.nuage_host
    nuage_port = args.nuage_port
    nuage_password = None
    if args.nuage_password:
        nuage_password = args.nuage_password
    nuage_username = args.nuage_username
    remove_policygroups = args.remove_policygroups
    nosslcheck = args.nosslcheck
    verbose = args.verbose
    vcenter_host = args.vcenter_host
    vcenter_https_port = args.vcenter_https_port
    vcenter_password = None
    if args.vcenter_password:
        vcenter_password = args.vcenter_password
    vcenter_username = args.vcenter_username

    # Logging settings
    if debug:
        log_level = logging.DEBUG
    elif verbose:
        log_level = logging.INFO
    else:
        log_level = logging.WARNING

    logging.basicConfig(filename=log_file, format='%(asctime)s %(levelname)s %(message)s', level=log_level)
    logger = logging.getLogger(__name__)

    # Disabling SSL verification if set
    ssl_context = None
    if nosslcheck:
        logger.debug('Disabling SSL certificate verification.')
        requests.packages.urllib3.disable_warnings()
        import ssl
        if hasattr(ssl, 'SSLContext'):
            ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
            ssl_context.verify_mode = ssl.CERT_NONE

    # Getting user password for Nuage connection
    if nuage_password is None:
        logger.debug('No command line Nuage password received, requesting Nuage password from user')
        nuage_password = getpass.getpass(
            prompt='Enter password for Nuage host {0:s} for user {1:s}: '.format(nuage_host, nuage_username))

    # Getting user password for vCenter connection
    if vcenter_password is None:
        logger.debug('No command line vCenter password received, requesting vCenter password from user')
        vcenter_password = getpass.getpass(
            prompt='Enter password for vCenter host {0:s} for user {1:s}: '.format(vcenter_host, vcenter_username))

    try:
        vc = None
        nc = None

        # Connecting to Nuage
        try:
            logger.info('Connecting to Nuage server {0:s}:{1:d} with username {2:s}'.format(nuage_host, nuage_port, nuage_username))
            nc = vsdk.NUVSDSession(username=nuage_username, password=nuage_password, enterprise=nuage_enterprise,
                                   api_url="https://{0:s}:{1:d}".format(nuage_host, nuage_port))
            nc.start()
        except IOError:
            pass

        if not nc or not nc.is_current_session():
            logger.error(
                'Could not connect to Nuage host {0:s} with user {1:s} and specified password'.format(nuage_host,
                                                                                                      nuage_username))
            return 1

        # Connecting to vCenter
        try:
            logger.info(
                'Connecting to vCenter server {0:s}:{1:d} with username {2:s}'.format(vcenter_host, vcenter_https_port,
                                                                                      vcenter_username))
            if ssl_context:
                vc = SmartConnect(host=vcenter_host, user=vcenter_username, pwd=vcenter_password,
                                  port=int(vcenter_https_port), sslContext=ssl_context)
            else:
                vc = SmartConnect(host=vcenter_host, user=vcenter_username, pwd=vcenter_password,
                                  port=int(vcenter_https_port))

        except IOError:
            pass

        if not vc:
            logger.error(
                'Could not connect to vCenter host {0:s} with user {1:s} and specified password'.format(vcenter_host,
                                                                                                        vcenter_username))
            return 1

        logger.debug('Registering vCenter disconnect at exit')
        atexit.register(Disconnect, vc)

        logger.info('Connected to both Nuage & vCenter servers')

    except vmodl.MethodFault, e:
        logger.critical('Caught vmodl fault: {0:s}'.format(e.msg))
        return 1
コード例 #9
0
ファイル: fip_overview.py プロジェクト: sunilvp/vspk-examples
def main():
    """
    Main function to handle vcenter vm names and the mapping to a policy group
    """

    # Handling arguments
    args = get_args()
    debug = args.debug
    json_output = args.json_output
    log_file = None
    if args.logfile:
        log_file = args.logfile
    nuage_enterprise = args.nuage_enterprise
    nuage_host = args.nuage_host
    nuage_port = args.nuage_port
    nuage_password = None
    if args.nuage_password:
        nuage_password = args.nuage_password
    nuage_username = args.nuage_username
    nosslcheck = args.nosslcheck
    verbose = args.verbose

    # Logging settings
    if debug:
        log_level = logging.DEBUG
    elif verbose:
        log_level = logging.INFO
    else:
        log_level = logging.WARNING

    logging.basicConfig(filename=log_file,
                        format='%(asctime)s %(levelname)s %(message)s',
                        level=log_level)
    logger = logging.getLogger(__name__)

    # Disabling SSL verification if set
    if nosslcheck:
        logger.debug('Disabling SSL certificate verification.')
        requests.packages.urllib3.disable_warnings()

    # Getting user password for Nuage connection
    if nuage_password is None:
        logger.debug(
            'No command line Nuage password received, requesting Nuage password from user'
        )
        nuage_password = getpass.getpass(
            prompt='Enter password for Nuage host %s for user %s: ' %
            (nuage_host, nuage_username))

    try:
        # Connecting to Nuage
        logger.info('Connecting to Nuage server %s:%s with username %s' %
                    (nuage_host, nuage_port, nuage_username))
        nc = vsdk.NUVSDSession(username=nuage_username,
                               password=nuage_password,
                               enterprise=nuage_enterprise,
                               api_url="https://%s:%s" %
                               (nuage_host, nuage_port))
        nc.start()

    except Exception, e:
        logger.error(
            'Could not connect to Nuage host %s with user %s and specified password'
            % (nuage_host, nuage_username))
        logger.critical('Caught exception: %s' % str(e))
        return 1
コード例 #10
0
    nuage_enterprise = args.nuage_enterprise

# Getting host for Nuage connection
nuage_host          = args.nuage_host

# Getting host port for Nuage connection
if args.nuage_port is None:
    logger.debug('No command line Nuage host port received, default will be used.')
    nuage_port = 8443
else:
    nuage_port = args.nuage_port

try:
    logger.info('Connecting to Nuage server %s:%s with username %s' % (nuage_host, nuage_port, nuage_username))
    nc = vspk.NUVSDSession(username=nuage_username,
                           password=nuage_password,
                           enterprise=nuage_enterprise,
                           api_url="https://{0}:{1}".format(nuage_host,nuage_port))
    nc.start()
    nuage_user = nc.user
except Exception, e:
    logger.error(
        'Could not connect to Nuage host %s with user %s and specified password' % (nuage_host, nuage_username))
    logger.critical('Caught exception: %s' % str(e))
    exit()
# Main logic
for subnet in nuage_user.subnets.get():
    if subnet.associated_shared_network_resource_id is not None:
        shared_net_obj = vspk.NUSharedNetworkResource(id=subnet.associated_shared_network_resource_id).fetch()[0]
        print('#'*10+'\n"{0}" subnet is associated with shared network "{1}"'.format(subnet.name,
                                                                                     shared_net_obj.name))
        print("This is full path to this subnet:\n{0}".format(' -> '.join(get_vsd_objects(subnet))))
コード例 #11
0
def main():
    """
    Main function to gather the information on the VM applied policies
    """
    global configuration, logger, output_parser

    # Handling arguments
    args = get_args()
    configuration = {}
    configuration['debug'] = args.debug
    configuration['json_output'] = args.json_output
    configuration['log_file'] = None
    if args.logfile:
        configuration['log_file'] = args.logfile
    configuration['nuage_enterprise'] = args.nuage_enterprise
    configuration['nuage_host'] = args.nuage_host
    configuration['nuage_port'] = args.nuage_port
    configuration['nuage_password'] = None
    if args.nuage_password:
        configuration['nuage_password'] = args.nuage_password
    configuration['nuage_username'] = args.nuage_username
    configuration['nosslcheck'] = args.nosslcheck
    configuration['verbose'] = args.verbose
    configuration['vm_names'] = []
    if args.vm_names:
        configuration['vm_names'] = args.vm_names

    # Logging settings
    if configuration['debug']:
        log_level = logging.DEBUG
    elif configuration['verbose']:
        log_level = logging.INFO
    else:
        log_level = logging.WARNING

    logging.basicConfig(filename=configuration['log_file'],
                        format='%(asctime)s %(levelname)s %(message)s',
                        level=log_level)
    logger = logging.getLogger(__name__)

    # Disabling SSL verification if set
    if configuration['nosslcheck']:
        logger.debug('Disabling SSL certificate verification.')
        requests.packages.urllib3.disable_warnings()

    # Getting user password for Nuage connection
    if configuration['nuage_password'] is None:
        logger.debug(
            'No command line Nuage password received, requesting Nuage password from user'
        )
        configuration['nuage_password'] = getpass.getpass(
            prompt='Enter password for Nuage host %s for user %s: ' %
            (configuration['nuage_host'], configuration['nuage_username']))

    try:
        # Connecting to Nuage
        logger.debug('Connecting to Nuage server %s:%s with username %s' %
                     (configuration['nuage_host'], configuration['nuage_port'],
                      configuration['nuage_username']))
        nc = vsdk.NUVSDSession(
            username=configuration['nuage_username'],
            password=configuration['nuage_password'],
            enterprise=configuration['nuage_enterprise'],
            api_url="https://%s:%s" %
            (configuration['nuage_host'], configuration['nuage_port']))
        nc.start()

    except Exception, e:
        logger.error(
            'Could not connect to Nuage host %s with user %s and specified password'
            % (configuration['nuage_host'], configuration['nuage_username']))
        logger.critical('Caught exception: %s' % str(e))
        return 1
コード例 #12
0
def main():
    """
    Main function to handle statistics
    """

    # Handling arguments
    args = get_args()
    debug = args.debug
    log_file = None
    if args.logfile:
        log_file = args.logfile
    mode = args.mode
    nuage_enterprise = args.nuage_enterprise
    nuage_host = args.nuage_host
    nuage_port = args.nuage_port
    nuage_password = None
    if args.nuage_password:
        nuage_password = args.nuage_password
    nuage_username = args.nuage_username
    nosslcheck = args.nosslcheck
    verbose = args.verbose
    nuage_vm_enterprise = args.nuage_vm_enterprise
    nuage_vm_domain = None
    if args.nuage_vm_domain:
        nuage_vm_domain = args.nuage_vm_domain
    nuage_vm_zone = None
    if args.nuage_vm_zone:
        nuage_vm_zone = args.nuage_vm_zone
    nuage_vm_subnet = args.nuage_vm_subnet
    nuage_vm_user = None
    if args.nuage_vm_user:
        nuage_vm_user = args.nuage_vm_user
    vcenter_host = args.vcenter_host
    vcenter_port = args.vcenter_port
    vcenter_password = None
    if args.vcenter_password:
        vcenter_password = args.vcenter_password
    vcenter_username = args.vcenter_username
    vcenter_portgroup = args.vcenter_portgroup
    vcenter_vm = args.vcenter_vm

    # Logging settings
    if debug:
        log_level = logging.DEBUG
    elif verbose:
        log_level = logging.INFO
    else:
        log_level = logging.WARNING

    logging.basicConfig(filename=log_file,
                        format='%(asctime)s %(levelname)s %(message)s',
                        level=log_level)
    logger = logging.getLogger(__name__)

    # Disabling SSL verification if set
    ssl_context = None
    if nosslcheck:
        logger.debug('Disabling SSL certificate verification.')
        requests.packages.urllib3.disable_warnings()
        import ssl
        if hasattr(ssl, 'SSLContext'):
            ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
            ssl_context.verify_mode = ssl.CERT_NONE

    # Getting user password for Nuage connection
    if nuage_password is None:
        logger.debug(
            'No command line Nuage password received, requesting Nuage password from user'
        )
        nuage_password = getpass.getpass(
            prompt='Enter password for Nuage host %s for user %s: ' %
            (nuage_host, nuage_username))

    # Getting user password for vCenter connection
    if vcenter_password is None:
        logger.debug(
            'No command line vCenter password received, requesting vCenter password from user'
        )
        vcenter_password = getpass.getpass(
            prompt='Enter password for vCenter host %s for user %s: ' %
            (vcenter_host, vcenter_username))

    try:
        vc = None
        nc = None

        # Connecting to Nuage
        logger.info('Connecting to Nuage server %s:%s with username %s' %
                    (nuage_host, nuage_port, nuage_username))
        nc = vsdk.NUVSDSession(username=nuage_username,
                               password=nuage_password,
                               enterprise=nuage_enterprise,
                               api_url="https://%s:%s" %
                               (nuage_host, nuage_port))
        nc.start()

        if not nc or not nc.is_current_session():
            logger.error(
                'Could not connect to Nuage host %s with user %s, enterprise %s and specified password'
                % (nuage_host, nuage_username, nuage_enterprise))
            return 1

        # Connecting to vCenter
        try:
            logger.info('Connecting to vCenter server %s:%s with username %s' %
                        (vcenter_host, vcenter_port, vcenter_username))
            if ssl_context:
                vc = SmartConnect(host=vcenter_host,
                                  user=vcenter_username,
                                  pwd=vcenter_password,
                                  port=int(vcenter_port),
                                  sslContext=ssl_context)
            else:
                vc = SmartConnect(host=vcenter_host,
                                  user=vcenter_username,
                                  pwd=vcenter_password,
                                  port=int(vcenter_port))
        except IOError, e:
            pass

        if not vc:
            logger.error(
                'Could not connect to vCenter host %s with user %s and specified password'
                % (vcenter_host, vcenter_username))
            return 1

        logger.info('Connected to both Nuage & vCenter servers')

        logger.debug('Registering vCenter disconnect at exit')
        atexit.register(Disconnect, vc)

        # Finding the Virtual Machine
        logger.debug('Searching for Virtual Machine: %s' % vcenter_vm)
        vc_vm = get_vcenter_object(logger, vc, [vim.VirtualMachine],
                                   vcenter_vm)
        if vc_vm is None:
            logger.critical('VM %s not found, ending run' % vcenter_vm)
            return 1

        # Finding the Portgroup
        logger.debug('Searching for Distributed Portgroup %s' %
                     vcenter_portgroup)
        vc_dvs_pg = get_vcenter_object(logger, vc,
                                       [vim.dvs.DistributedVirtualPortgroup],
                                       vcenter_portgroup)
        if vc_dvs_pg is None:
            logger.critical('Unknown distributed portgroup %s, exiting' %
                            vcenter_portgroup)
            return 1

        # Finding enterprise
        logger.debug('Searching for enterprise %s' % nuage_vm_enterprise)
        nc_enterprise = get_nuage_object(logger, nc.user, 'ENTERPRISE',
                                         'name == "%s"' % nuage_vm_enterprise,
                                         True)
        if nc_enterprise is None:
            logger.critical('Unknown enterprise %s, exiting' %
                            nuage_vm_enterprise)
            return 1

        # Finding subnet
        logger.debug(
            'Searching for the subnet, first by looking at the subnet itself.')
        nc_subnet = None
        nc_subnets = get_nuage_object(logger, nc.user, 'SUBNET',
                                      'name == "%s"' % nuage_vm_subnet, False)

        if len(nc_subnets) == 1:
            logger.debug('Found the L3 subnet %s in Nuage' % nuage_vm_subnet)
            nc_subnet = nc_subnets[0]
        elif len(nc_subnets) == 0:
            logger.debug(
                'Found no L3 subnet with name %s, checking L2 domains' %
                nuage_vm_subnet)
            nc_subnet = get_nuage_object(logger, nc_enterprise, 'L2DOMAIN',
                                         'name == "%s"' % nuage_vm_subnet,
                                         True)
        elif len(
                nc_subnets
        ) > 1 and nuage_vm_domain is not None and nuage_vm_zone is not None:
            logger.debug(
                'Found more than one L3 subnet with name %s, using Domain %s and Zone %s to find the right subnet'
                % (nuage_vm_subnet, nuage_vm_domain, nuage_vm_zone))
            nc_domain = get_nuage_object(logger, nc_enterprise, 'DOMAIN',
                                         'name == "%s"' % nuage_vm_domain,
                                         True)
            if nc_domain is None:
                logger.critical(
                    'Domain %s does not exist in Enterprise %s, exiting' %
                    (nuage_vm_domain, nuage_vm_zone))
                return 1
            nc_zone = get_nuage_object(logger, nc_domain, 'ZONE',
                                       'name == "%s"' % nuage_vm_zone, True)
            if nc_zone is None:
                logger.critical(
                    'Zone %s does not exist in Domain %s in Enterprise %s, exiting'
                    % (nuage_vm_zone, nuage_vm_domain, nuage_vm_enterprise))
                return 1
            nc_subnet = get_nuage_object(logger, nc_zone, 'SUBNET',
                                         'name == "%s"' % nuage_vm_subnet,
                                         False)

        if nc_subnet is None:
            logger.critical(
                'Subnet with name %s does not exist as an L3 subnet or an L2 domain, exiting'
            )
            return 1

        # Getting VM UUID
        logger.debug('Getting VM UUID, MAC & IP')
        vc_vm_uuid = vc_vm.config.uuid
        logger.debug('Found UUID %s for VM %s' % (vc_vm_uuid, vcenter_vm))
        vc_vm_net_info = vc_vm.guest.net
        vc_vm_mac = None
        vc_vm_ip = None

        for cur_net in vc_vm_net_info:
            if cur_net.macAddress:
                logger.debug('Mac address %s found for VM %s' %
                             (cur_net.macAddress, vcenter_vm))
                vc_vm_mac = cur_net.macAddress
            if vc_vm_mac and cur_net.ipConfig:
                if cur_net.ipConfig.ipAddress:
                    for cur_ip in cur_net.ipConfig.ipAddress:
                        logger.debug('Checking ip address %s for VM %s' %
                                     (cur_ip.ipAddress, vcenter_vm))
                        if re.match('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',
                                    cur_ip.ipAddress
                                    ) and cur_ip.ipAddress != '127.0.0.1':
                            vc_vm_ip = cur_ip.ipAddress
                            break
            if vc_vm_mac and vc_vm_ip:
                logger.debug('Found MAC %s and IP %s for VM %s' %
                             (vc_vm_mac, vc_vm_ip, vcenter_vm))
                break

        # Check if IP is in subnet
        logger.debug('Verifying that IP %s of VM %s is part of subnet %s' %
                     (vc_vm_ip, vcenter_vm, nuage_vm_subnet))
        if not ipaddress.ip_address(unicode(
                vc_vm_ip, 'utf-8')) in ipaddress.ip_network(
                    '%s/%s' % (nc_subnet.address, nc_subnet.netmask)):
            logger.critical('IP %s is not part of subnet %s with netmask %s' %
                            (vc_vm_ip, nc_subnet.address, nc_subnet.netmask))
            return 1

        logger.info('Found UUID %s, MAC %s and IP %s for VM %s' %
                    (vc_vm_uuid, vc_vm_mac, vc_vm_ip, vcenter_vm))

        # if metadata mode, create metadata on the VM
        if mode.lower() == 'metadata':
            logger.debug('Setting the metadata on VM %s' % vcenter_vm)
            vm_option_values = []
            # Network type
            vm_option_values.append(
                vim.option.OptionValue(key='nuage.nic0.networktype',
                                       value='ipv4'))
            # User
            vm_option_values.append(
                vim.option.OptionValue(key='nuage.user', value=nuage_vm_user))
            # IP
            vm_option_values.append(
                vim.option.OptionValue(key='nuage.nic0.ip', value=vc_vm_ip))
            if type(nc_subnet) is vsdk.NUSubnet:
                nc_zone = vsdk.NUZone(id=nc_subnet.parent_id)
                nc_zone.fetch()
                nc_domain = vsdk.NUDomain(id=nc_zone.parent_id)
                nc_domain.fetch()
                nc_enterprise = vsdk.NUEnterprise(id=nc_domain.parent_id)
                nc_enterprise.fetch()
                # Enterprise
                vm_option_values.append(
                    vim.option.OptionValue(key='nuage.enterprise',
                                           value=nc_enterprise.name))
                # Domain
                vm_option_values.append(
                    vim.option.OptionValue(key='nuage.nic0.domain',
                                           value=nc_domain.name))
                # Zone
                vm_option_values.append(
                    vim.option.OptionValue(key='nuage.nic0.zone',
                                           value=nc_zone.name))
                # Subnet
                vm_option_values.append(
                    vim.option.OptionValue(key='nuage.nic0.network',
                                           value=nc_subnet.name))
            else:
                nc_enterprise = vsdk.NUEnterprise(id=nc_subnet.parent_id)
                nc_enterprise.fetch()
                # Enterprise
                vm_option_values.append(
                    vim.option.OptionValue(key='nuage.enterprise',
                                           value=nc_enterprise.name))
                # L2Domain
                vm_option_values.append(
                    vim.option.OptionValue(key='nuage.nic0.l2domain',
                                           value=nc_subnet.name))

            logger.debug('Creating of config spec for VM')
            config_spec = vim.vm.ConfigSpec(extraConfig=vm_option_values)
            logger.info(
                'Applying advanced parameters. This might take a couple of seconds'
            )
            config_task = vc_vm.ReconfigVM_Task(spec=config_spec)
            logger.debug('Waiting for the advanced paramerter to be applied')
            run_loop = True
            while run_loop:
                info = config_task.info
                if info.state == vim.TaskInfo.State.success:
                    logger.debug('Advanced parameters applied')
                    run_loop = False
                    break
                elif info.state == vim.TaskInfo.State.error:
                    if info.error.fault:
                        logger.info(
                            'Applying advanced parameters has quit with error: %s'
                            % info.error.fault.faultMessage)
                    else:
                        logger.info(
                            'Applying advanced parameters has quit with cancelation'
                        )
                    run_loop = False
                    break
                sleep(1)
        # Else if mode split-activation, create vPort and VM
        elif mode.lower() == 'split-activation':
            # Creating vPort
            logger.debug('Creating vPort for VM %s' % vcenter_vm)
            nc_vport = vsdk.NUVPort(
                name=vcenter_vm,
                address_spoofing='INHERITED',
                type='VM',
                description='Automatically created, do not edit.')
            nc_subnet.create_child(nc_vport)
            # Creating VM
            logger.debug('Creating a Nuage VM for VM %s' % vcenter_vm)
            nc_vm = vsdk.NUVM(name=vcenter_vm,
                              uuid=vc_vm_uuid,
                              interfaces=[{
                                  'name': vcenter_vm,
                                  'VPortID': nc_vport.id,
                                  'MAC': vc_vm_mac,
                                  'IPAddress': vc_vm_ip
                              }])
            nc.user.create_child(nc_vm)

        # Fetching nic from the VM
        logger.debug('Searching for NIC on VM %s' % vcenter_vm)
        vc_vm_nic = None
        for device in vc_vm.config.hardware.device:
            if isinstance(device, vim.vm.device.VirtualEthernetCard):
                logger.debug('Found NIC for VM %s' % vcenter_vm)
                vc_vm_nic = device
                break

        if vc_vm_nic is None:
            logger.critical('Could not find NIC for VM %s, exiting' %
                            vcenter_vm)
            return 1

        # Switching VM nic
        logger.debug('Creating spec to reconfigure the NIC of VM %s' %
                     vcenter_vm)
        vc_nicspec = vim.vm.device.VirtualDeviceSpec()
        vc_nicspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
        vc_nicspec.device = vc_vm_nic
        vc_nicspec.device.wakeOnLanEnabled = True
        vc_nicspec.device.backing = vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo(
        )
        vc_nicspec.device.backing.port = vim.dvs.PortConnection()
        vc_nicspec.device.backing.port.portgroupKey = vc_dvs_pg.key
        vc_nicspec.device.backing.port.switchUuid = vc_dvs_pg.config.distributedVirtualSwitch.uuid
        vc_nicspec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo(
        )
        vc_nicspec.device.connectable.startConnected = True
        vc_nicspec.device.connectable.connected = True
        vc_nicspec.device.connectable.allowGuestControl = True
        vc_vm_nic_reconfig = vim.vm.ConfigSpec(deviceChange=[vc_nicspec])

        logger.info(
            'Applying NIC changes. This might take a couple of seconds')
        config_task = vc_vm.ReconfigVM_Task(spec=vc_vm_nic_reconfig)
        logger.debug('Waiting for the nic change to be applied')
        run_loop = True
        while run_loop:
            info = config_task.info
            if info.state == vim.TaskInfo.State.success:
                logger.debug('Nic change applied')
                run_loop = False
                break
            elif info.state == vim.TaskInfo.State.error:
                if info.error.fault:
                    logger.info(
                        'Applying nic changes has quit with error: %s' %
                        info.error.fault.faultMessage)
                else:
                    logger.info(
                        'Applying nic changes has quit with cancelation')
                run_loop = False
                break
            sleep(1)

        logger.info(
            'Succesfully attached VM %s to Nuage subnet %s, in mode %s' %
            (vcenter_vm, nuage_vm_subnet, mode))
コード例 #13
0
def main():
    """
    Manage the activation of a vSphere VM
    """
    # Handling arguments
    args = get_args()

    if args.config_file:
        cfg = parse_config(args.config_file)
    elif os.path.isfile('{0:s}/.nuage/config.ini'.format(
            os.path.expanduser('~'))):
        cfg = parse_config('{0:s}/.nuage/config.ini'.format(
            os.path.expanduser('~')))
    else:
        print 'Missing config file'
        return 1

    mode = args.mode

    nuage_vm_enterprise = None
    if args.nuage_vm_enterprise:
        nuage_vm_enterprise = args.nuage_vm_enterprise
    nuage_vm_domain = None
    if args.nuage_vm_domain:
        nuage_vm_domain = args.nuage_vm_domain
    nuage_vm_zone = None
    if args.nuage_vm_zone:
        nuage_vm_zone = args.nuage_vm_zone
    nuage_vm_subnet = None
    if args.nuage_vm_subnet:
        nuage_vm_subnet = args.nuage_vm_subnet
    nuage_vm_ip = None
    if args.nuage_vm_ip:
        nuage_vm_ip = args.nuage_vm_ip
    nuage_vm_user = None
    if args.nuage_vm_user:
        nuage_vm_user = args.nuage_vm_user
    nuage_vm_policy_group = None
    if args.nuage_vm_policy_group:
        nuage_vm_user = args.nuage_vm_policy_group
    nuage_vm_redirection_target = None
    if args.nuage_vm_redirection_target:
        nuage_vm_user = args.nuage_vm_redirection_target
    vcenter_vm_name = None
    if args.vcenter_vm_name:
        vcenter_vm_name = args.vcenter_vm_name

    # Handling logging
    log_dir = cfg.get('LOG', 'directory')
    log_file = cfg.get('LOG', 'file')
    log_level = cfg.get('LOG', 'level')

    if not log_level:
        log_level = 'ERROR'

    log_path = None
    if log_dir and log_file and os.path.isdir(log_dir) and os.access(
            log_dir, os.W_OK):
        log_path = os.path.join(log_dir, log_file)

    logging.basicConfig(
        filename=log_path,
        format='%(asctime)s %(levelname)s - %(name)s - %(message)s',
        level=log_level)
    logging.info('Logging initiated')

    # Disabling SSL verification if set
    logging.debug('Disabling SSL certificate verification.')
    requests.packages.urllib3.disable_warnings()

    try:
        vc = None
        nc = None

        # Connecting to Nuage
        try:
            logging.info(
                'Connecting to Nuage server {0:s} with username {1:s} and enterprise {2:s}'
                .format(cfg.get('NUAGE', 'vsd_api_url'),
                        cfg.get('NUAGE', 'vsd_api_user'),
                        cfg.get('NUAGE', 'vsd_api_enterprise')))
            nc = vsdk.NUVSDSession(username=cfg.get('NUAGE', 'vsd_api_user'),
                                   password=cfg.get('NUAGE',
                                                    'vsd_api_password'),
                                   enterprise=cfg.get('NUAGE',
                                                      'vsd_api_enterprise'),
                                   api_url=cfg.get('NUAGE', 'vsd_api_url'))
            nc.start()
        except IOError:
            pass

        if not nc or not nc.is_current_session():
            logging.error(
                'Could not connect to Nuage host {0:s} with user {1:s}, enterprise {2:s} and specified password'
                .format(cfg.get('NUAGE', 'vsd_api_url'),
                        cfg.get('NUAGE', 'vsd_api_user'),
                        cfg.get('NUAGE', 'vsd_api_enterprise')))
            return 1

        # Connecting to vCenter
        try:
            logging.info(
                'Connecting to vCenter server {0:s} with username {1:s}'.
                format(cfg.get('VSPHERE', 'vsphere_api_host'),
                       cfg.get('VSPHERE', 'vsphere_api_user')))
            vc = SmartConnect(host=cfg.get('VSPHERE', 'vsphere_api_host'),
                              user=cfg.get('VSPHERE', 'vsphere_api_user'),
                              pwd=cfg.get('VSPHERE', 'vsphere_api_password'),
                              port=int(cfg.get('VSPHERE', 'vsphere_api_port')))
        except IOError:
            pass

        if not vc:
            logging.error(
                'Could not connect to vCenter host {0:s} with user {1:s} and specified password'
                .format(cfg.get('VSPHERE', 'vsphere_api_host'),
                        cfg.get('VSPHERE', 'vsphere_api_user')))
            return 1

        logging.info('Connected to both Nuage & vCenter servers')

        logging.debug('Registering vCenter disconnect at exit')
        atexit.register(Disconnect, vc)

        vcenter_vm = None
        vm_enterprise = None
        vm_user = None
        vm_domain = None
        vm_is_l2domain = False
        vm_zone = None
        vm_subnet = None
        vm_ip = None
        vm_policy_group = None
        vm_redirection_target = None
        # Verifying the vCenter VM existence or selecting it
        if vcenter_vm_name:
            vcenter_vm = find_vm(vc, vcenter_vm_name)
            if vcenter_vm is None:
                logging.critical(
                    'Unable to find specified VM with name {0:s}'.format(
                        vcenter_vm_name))
                return 1
        else:
            logging.debug('Offering a choice of which VM to activate')
            content = vc.content
            obj_view = content.viewManager.CreateContainerView(
                content.rootFolder, [vim.VirtualMachine], True)
            vm_list = obj_view.view
            clear()
            print('Please select your VM:')
            index = 0
            for cur_vm in vm_list:
                print('%s. %s' % (index + 1, cur_vm.name))
                index += 1
            while vcenter_vm is None:
                choice = raw_input(
                    'Please enter the number of the VM [1-%s]: ' %
                    len(vm_list))
                choice = int(choice)
                if choice > 0 and choice - 1 < len(vm_list):
                    vcenter_vm = vm_list[choice - 1]
                    break
                print('Invalid choice, please try again')

        # Verifying the Nuage Enterprise existence or selecting it
        if nuage_vm_enterprise:
            logging.debug('Finding Nuage enterprise %s' % nuage_vm_enterprise)
            vm_enterprise = nc.user.enterprises.get_first(
                filter="name == '%s'" % nuage_vm_enterprise)
            if vm_enterprise is None:
                logging.error('Unable to find Nuage enterprise %s' %
                              nuage_vm_enterprise)
                return 1
            logging.info('Nuage enterprise %s found' % nuage_vm_enterprise)
        else:
            clear()
            print('VM: %s' % vcenter_vm.name)
            print(80 * '-')
            print('Please select your enterprise:')
            index = 0
            all_ent = nc.user.enterprises.get()
            for cur_ent in all_ent:
                print('%s. %s' % (index + 1, cur_ent.name))
                index += 1
            while vm_enterprise is None:
                choice = raw_input(
                    'Please enter the number of the enterprise [1-%s]: ' %
                    len(all_ent))
                choice = int(choice)
                if choice > 0 and choice - 1 < len(all_ent):
                    vm_enterprise = all_ent[choice - 1]
                    break
                print('Invalid choice, please try again')

        # Verifying the Nuage User existence or selecting it
        if nuage_vm_user:
            logging.debug('Finding Nuage user %s' % nuage_vm_user)
            vm_user = vm_enterprise.users.get_first(filter="userName == '%s'" %
                                                    nuage_vm_user)
            if vm_user is None:
                logging.error('Unable to find Nuage user %s' % nuage_vm_user)
                return 1
            logging.info('Nuage user %s found' % nuage_vm_user)
        else:
            clear()
            print('VM: %s' % vcenter_vm.name)
            print('Enterprise: %s' % vm_enterprise.name)
            print(80 * '-')
            print('Please select your user:'******'%s. %s' % (index + 1, cur_user.user_name))
                index += 1
            while vm_user is None:
                choice = raw_input(
                    'Please enter the number of the user [1-%s]: ' %
                    len(all_users))
                choice = int(choice)
                if choice > 0 and choice - 1 < len(all_users):
                    vm_user = all_users[choice - 1]
                    break
                print('Invalid choice, please try again')

        # Verifying the Nuage Domain existence or selecting it
        if nuage_vm_domain:
            logging.debug('Finding Nuage domain %s' % nuage_vm_domain)
            vm_domain = vm_enterprise.domains.get_first(filter="name == '%s'" %
                                                        nuage_vm_domain)
            if vm_domain is None:
                logging.debug(
                    'Unable to find the domain {0:s} as an L3 domain'.format(
                        nuage_vm_domain))
                vm_domain = vm_enterprise.l2_domains.get_first(
                    filter="name == '%s'" % nuage_vm_domain)
                vm_is_l2domain = True
                if vm_domain is None:
                    logging.error('Unable to find Nuage domain {0:s}'.format(
                        nuage_vm_domain))
                    return 1
            logging.info('Nuage domain %s found' % nuage_vm_domain)
        else:
            clear()
            print('VM: %s' % vcenter_vm.name)
            print('Enterprise: %s' % vm_enterprise.name)
            print('User: %s' % vm_user.user_name)
            print(80 * '-')
            print('Please select your domain:')
            index = 0
            all_l3_dom = vm_enterprise.domains.get()
            all_l2_dom = vm_enterprise.l2_domains.get()
            all_dom = all_l2_dom + all_l3_dom
            for cur_dom in all_l2_dom:
                print('%s. L2 %s - %s/%s' % (index + 1, cur_dom.name,
                                             cur_dom.address, cur_dom.netmask))
                index += 1
            for cur_dom in all_l3_dom:
                print('%s. L3 - %s' % (index + 1, cur_dom.name))
                index += 1
            while vm_domain is None:
                choice = raw_input(
                    'Please enter the number of the domain [1-%s]: ' %
                    len(all_dom))
                choice = int(choice)
                if choice > 0 and choice - 1 < len(all_dom):
                    vm_domain = all_dom[choice - 1]
                    if type(vm_domain) is vsdk.NUL2Domain:
                        vm_is_l2domain = True
                    break
                print('Invalid choice, please try again')

        # Verifying the Nuage Zone existence or selecting it
        if not vm_is_l2domain and nuage_vm_zone:
            logging.debug('Finding Nuage zone %s' % nuage_vm_zone)
            vm_zone = vm_domain.zones.get_first(filter="name == '%s'" %
                                                nuage_vm_zone)
            if vm_zone is None:
                logging.error('Unable to find Nuage zone %s' % nuage_vm_zone)
                return 1
            logging.info('Nuage zone %s found' % nuage_vm_zone)
        elif not vm_is_l2domain:
            clear()
            print('VM: %s' % vcenter_vm.name)
            print('Enterprise: %s' % vm_enterprise.name)
            print('User: %s' % vm_user.user_name)
            print('Domain: %s' % vm_domain.name)
            print(80 * '-')
            print('Please select your zone:')
            index = 0
            all_zone = vm_domain.zones.get()
            for cur_zone in all_zone:
                print('%s. %s' % (index + 1, cur_zone.name))
                index += 1
            while vm_zone is None:
                choice = raw_input(
                    'Please enter the number of the zone [1-%s]: ' %
                    len(all_zone))
                choice = int(choice)
                if choice > 0 and choice - 1 < len(all_zone):
                    vm_zone = all_zone[choice - 1]
                    break
                print('Invalid choice, please try again')

        # Verifying the Nuage Subnet existence or selecting it
        if not vm_is_l2domain and nuage_vm_subnet:
            logging.debug('Finding Nuage subnet %s' % nuage_vm_subnet)
            vm_subnet = vm_zone.subnets.get_first(filter="name == '%s'" %
                                                  nuage_vm_subnet)
            if vm_subnet is None:
                logging.error('Unable to find Nuage subnet %s' %
                              nuage_vm_subnet)
                return 1
            logging.info('Nuage subnet %s found' % nuage_vm_subnet)
        elif not vm_is_l2domain:
            clear()
            print('VM: %s' % vcenter_vm.name)
            print('Enterprise: %s' % vm_enterprise.name)
            print('User: %s' % vm_user.user_name)
            print('Domain: %s' % vm_domain.name)
            print('Zone: %s' % vm_zone.name)
            print(80 * '-')
            print('Please select your subnet:')
            index = 0
            all_subnet = vm_zone.subnets.get()
            for cur_subnet in all_subnet:
                print('%s. %s - %s/%s' %
                      (index + 1, cur_subnet.name, cur_subnet.address,
                       cur_subnet.netmask))
                index += 1
            while vm_subnet is None:
                choice = raw_input(
                    'Please enter the number of the subnet [1-%s]: ' %
                    len(all_subnet))
                choice = int(choice)
                if choice > 0 and choice - 1 < len(all_subnet):
                    vm_subnet = all_subnet[choice - 1]
                    break
                print('Invalid choice, please try again')

        # Verifying the IP or asking for it
        if nuage_vm_ip:
            logging.debug(
                'Verifying if IP %s is inside Nuage subnet %s range' %
                (nuage_vm_ip, vm_subnet.name))
            if not ipaddress.ip_address(nuage_vm_ip) in ipaddress.ip_network(
                    '%s/%s' % (vm_subnet.address, vm_subnet.netmask)):
                logging.error(
                    'IP %s is not part of subnet %s with netmask %s' %
                    (nuage_vm_ip, vm_subnet.address, vm_subnet.netmask))
                return 1
            vm_ip = nuage_vm_ip
        else:
            clear()
            print('VM: %s' % vcenter_vm.name)
            print('Enterprise: %s' % vm_enterprise.name)
            print('User: %s' % vm_user.user_name)
            if not vm_is_l2domain:
                print('Domain: %s' % vm_domain.name)
                print('Zone: %s' % vm_zone.name)
                print('Subnet: %s - %s/%s' %
                      (vm_subnet.name, vm_subnet.address, vm_subnet.netmask))
            else:
                print('Domain: %s - %s/%s' %
                      (vm_domain.name, vm_domain.address, vm_domain.netmask))
            print(80 * '-')
            print(
                'If you want a static IP, please enter it. Or press enter for a DHCP assigned IP.'
            )
            while vm_ip is None:
                choice = raw_input(
                    'Please enter the IP or press enter for a DHCP assigned IP: '
                )
                if not choice or ipaddress.ip_address(
                        choice) in ipaddress.ip_network(
                            '%s/%s' % (vm_subnet.address, vm_subnet.netmask)):
                    vm_ip = choice
                    break
                print('Invalid choice, please try again')

        # Verifying the Nuage policy group existence or selecting it
        if nuage_vm_policy_group:
            logging.debug('Finding Nuage policy group %s' %
                          nuage_vm_policy_group)
            vm_policy_group = vm_domain.policy_groups.get_first(
                filter="name == '%s'" % nuage_vm_policy_group)
            if vm_policy_group is None:
                logging.error('Unable to find Nuage policy group {0:s}'.format(
                    nuage_vm_policy_group))
                return 1
            logging.info('Nuage policy group %s found' % nuage_vm_policy_group)
        else:
            clear()
            print('VM: %s' % vcenter_vm.name)
            print('Enterprise: %s' % vm_enterprise.name)
            print('User: %s' % vm_user.user_name)
            if not vm_is_l2domain:
                print('Domain: %s' % vm_domain.name)
                print('Zone: %s' % vm_zone.name)
                print('Subnet: %s - %s/%s' %
                      (vm_subnet.name, vm_subnet.address, vm_subnet.netmask))
            else:
                print('Domain: %s - %s/%s' %
                      (vm_domain.name, vm_domain.address, vm_domain.netmask))
            if vm_ip:
                print('IP: {0:s}'.format(vm_ip))
            print(80 * '-')
            print('Please select your policy group:')
            index = 0
            all_pg = vm_domain.policy_groups.get()
            print('0. None')
            for cur_pg in all_pg:
                print('%s. %s' % (index + 1, cur_pg.name))
                index += 1
            while vm_policy_group is None:
                choice = raw_input(
                    'Please enter the number of the policy group [0-%s]: ' %
                    len(all_pg))
                choice = int(choice)
                if choice == 0:
                    vm_policy_group = None
                    break
                elif choice > 0 and choice - 1 < len(all_pg):
                    vm_policy_group = all_pg[choice - 1]
                    break
                print('Invalid choice, please try again')

        # Verifying the Nuage redirection target existence or selecting it
        if nuage_vm_redirection_target:
            logging.debug('Finding Nuage redirection target %s' %
                          nuage_vm_redirection_target)
            vm_redirection_target = vm_domain.redirection_targets.get_first(
                filter="name == '%s'" % nuage_vm_redirection_target)
            if vm_redirection_target is None:
                logging.error(
                    'Unable to find Nuage redirection target {0:s}'.format(
                        nuage_vm_redirection_target))
                return 1
            logging.info('Nuage redirection target %s found' %
                         nuage_vm_redirection_target)
        else:
            clear()
            print('VM: %s' % vcenter_vm.name)
            print('Enterprise: %s' % vm_enterprise.name)
            print('User: %s' % vm_user.user_name)
            if not vm_is_l2domain:
                print('Domain: %s' % vm_domain.name)
                print('Zone: %s' % vm_zone.name)
                print('Subnet: %s - %s/%s' %
                      (vm_subnet.name, vm_subnet.address, vm_subnet.netmask))
            else:
                print('Domain: %s - %s/%s' %
                      (vm_domain.name, vm_domain.address, vm_domain.netmask))
            if vm_ip:
                print('IP: {0:s}'.format(vm_ip))
            if vm_policy_group:
                print('Policy group: {0:s}'.format(vm_policy_group.name))
            print(80 * '-')
            print('Please select your redirection target:')
            index = 0
            all_rt = vm_domain.redirection_targets.get()
            print('0. None')
            for cur_rt in all_rt:
                print('%s. %s' % (index + 1, cur_rt.name))
                index += 1
            while vm_redirection_target is None:
                choice = raw_input(
                    'Please enter the number of the redirection target [0-%s]: '
                    % len(all_rt))
                choice = int(choice)
                if choice == 0:
                    vm_redirection_target = None
                    break
                elif choice > 0 and choice - 1 < len(all_rt):
                    vm_redirection_target = all_rt[choice - 1]
                    break
                print('Invalid choice, please try again')

        logging.info('Using following Nuage values:')
        logging.info('Enterprise: %s' % vm_enterprise.name)
        logging.info('User: %s' % vm_user.user_name)
        if not vm_is_l2domain:
            logging.info('Domain: %s' % vm_domain.name)
            logging.info('Zone: %s' % vm_zone.name)
            logging.info(
                'Subnet: %s - %s/%s' %
                (vm_subnet.name, vm_subnet.address, vm_subnet.netmask))
        else:
            logging.info(
                'Domain: %s - %s/%s' %
                (vm_domain.name, vm_domain.address, vm_domain.netmask))
        if vm_ip:
            logging.info('Static IP: %s' % vm_ip)
        if vm_policy_group:
            logging.info('Policy group: {0:s}'.format(vm_policy_group.name))
        if vm_redirection_target:
            logging.info('Redirection target: {0:s}'.format(
                vm_redirection_target.name))

        clear()

        if mode == 'metadata':
            print('Setting Nuage Metadata on VM')
            # Setting Nuage metadata
            logging.info('Setting Nuage Metadata')
            vm_option_values = []
            # Enterprise
            vm_option_values.append(
                vim.option.OptionValue(key='nuage.enterprise',
                                       value=vm_enterprise.name))
            if vm_is_l2domain:
                # L2 Domain
                vm_option_values.append(
                    vim.option.OptionValue(key='nuage.nic0.l2domain',
                                           value=vm_domain.name))
            else:
                # Domain
                vm_option_values.append(
                    vim.option.OptionValue(key='nuage.nic0.domain',
                                           value=vm_domain.name))
                # Zone
                vm_option_values.append(
                    vim.option.OptionValue(key='nuage.nic0.zone',
                                           value=vm_zone.name))
                # Subnet
                vm_option_values.append(
                    vim.option.OptionValue(key='nuage.nic0.network',
                                           value=vm_subnet.name))
            # Network type
            vm_option_values.append(
                vim.option.OptionValue(key='nuage.nic0.networktype',
                                       value='ipv4'))
            # User
            vm_option_values.append(
                vim.option.OptionValue(key='nuage.user',
                                       value=vm_user.user_name))
            # IP
            if vm_ip:
                vm_option_values.append(
                    vim.option.OptionValue(key='nuage.nic0.ip', value=vm_ip))
            # Policy group
            if vm_policy_group:
                vm_option_values.append(
                    vim.option.OptionValue(key='nuage.nic0.policy-group',
                                           value=vm_policy_group.name))
            # Redirection target
            if vm_redirection_target:
                vm_option_values.append(
                    vim.option.OptionValue(key='nuage.nic0.redirection-target',
                                           value=vm_redirection_target.name))

            logging.debug('Creating of config spec for VM')
            config_spec = vim.vm.ConfigSpec(extraConfig=vm_option_values)
            logging.info(
                'Applying advanced parameters. This might take a couple of seconds'
            )
            config_task = vcenter_vm.ReconfigVM_Task(spec=config_spec)
            logging.debug('Waiting for the advanced paramerter to be applied')
            while True:
                info = config_task.info
                if info.state == vim.TaskInfo.State.success:
                    logging.debug('Advanced parameters applied')
                    break
                elif info.state == vim.TaskInfo.State.error:
                    if info.error.fault:
                        logging.info(
                            'Applying advanced parameters has quit with error: %s'
                            % info.error.fault.faultMessage)
                    else:
                        logging.info(
                            'Applying advanced parameters has quit with cancelation'
                        )
                    break
                sleep(5)

        elif mode == 'split-activation':
            print('Creating vPort and VM in VSD for split activation')
            logging.debug('Starting split activation')

            # Getting VM UUID
            logging.debug('Getting VM UUID, MAC & IP')
            vcenter_vm_uuid = vcenter_vm.config.uuid
            logging.debug('Found UUID %s for VM %s' %
                          (vcenter_vm_uuid, vcenter_vm.name))
            vcenter_vm_mac = None
            vcenter_vm_hw = vcenter_vm.config.hardware
            for dev in vcenter_vm_hw.device:
                if isinstance(dev, vim.vm.device.VirtualEthernetCard):
                    if dev.macAddress:
                        logging.debug('Found MAC {0:s} for VM {1:s}'.format(
                            dev.macAddress, vcenter_vm.name))
                        vcenter_vm_mac = dev.macAddress
                        break

            if vcenter_vm_mac is None:
                logging.critical('Unable to find a valid mac address for VM')
                return 1

            # Creating vPort
            logging.debug('Creating vPort for VM %s' % vcenter_vm.name)
            nc_vport = vsdk.NUVPort(
                name='{0:s}-vport'.format(vcenter_vm.name),
                address_spoofing='INHERITED',
                type='VM',
                description='Automatically created, do not edit.')
            if vm_is_l2domain:
                vm_domain.create_child(nc_vport)
            else:
                vm_subnet.create_child(nc_vport)

            # Creating VM
            logging.debug('Creating a Nuage VM for VM %s' % vcenter_vm)
            nc_vm = vsdk.NUVM(name=vcenter_vm.name,
                              uuid=vcenter_vm_uuid,
                              interfaces=[{
                                  'name': vcenter_vm_mac,
                                  'VPortID': nc_vport.id,
                                  'MAC': vcenter_vm_mac
                              }])
            nc.user.create_child(nc_vm)

        else:
            logging.critical('Invalid mode')
            return 1

    except vmodl.MethodFault, e:
        logging.critical('Caught vmodl fault: {0:s}'.format(e.msg))
        return 1
コード例 #14
0
def main():
    """
    Backup the vCenter Integration Node configuration
    """

    # Handling arguments
    args = get_args()
    debug = args.debug
    log_file = None
    if args.logfile:
        log_file = args.logfile
    nuage_enterprise = args.nuage_enterprise
    nuage_host = args.nuage_host
    nuage_port = args.nuage_port
    nuage_password = None
    if args.nuage_password:
        nuage_password = args.nuage_password
    nuage_username = args.nuage_username
    output_folder = args.output_folder
    nosslcheck = args.nosslcheck
    verbose = args.verbose
    # Logging settings
    if debug:
        log_level = logging.DEBUG
    elif verbose:
        log_level = logging.INFO
    else:
        log_level = logging.WARNING

    logging.basicConfig(filename=log_file,
                        format='%(asctime)s %(levelname)s %(message)s',
                        level=log_level)
    logger = logging.getLogger(__name__)

    # Checking if folder is writeable
    if not os.access(output_folder, os.W_OK):
        logger.critical(
            'Folder {0:s} is not writable, exiting.'.format(output_folder))
        return 1

    # Disabling SSL verification if set
    ssl_context = None
    if nosslcheck:
        logger.debug('Disabling SSL certificate verification.')
        requests.packages.urllib3.disable_warnings()

    # Getting user password for Nuage connection
    if nuage_password is None:
        logger.debug(
            'No command line Nuage password received, requesting Nuage password from user'
        )
        nuage_password = getpass.getpass(
            prompt='Enter password for Nuage host {0:s} for user {1:s}: '.
            format(nuage_host, nuage_username))

    nc = None

    # Connecting to Nuage
    try:
        logger.info(
            'Connecting to Nuage server {0:s}:{1:d} with username {2:s}'.
            format(nuage_host, nuage_port, nuage_username))
        nc = vsdk.NUVSDSession(username=nuage_username,
                               password=nuage_password,
                               enterprise=nuage_enterprise,
                               api_url="https://{0:s}:{1:d}".format(
                                   nuage_host, nuage_port))
        nc.start()
    except IOError, e:
        pass
コード例 #15
0
def main():
    """
    Main function to handle vcenter vm names and the mapping to a policy group
    """
    global logger, configuration, nc, nc_enterprise, nc_domain, nc_subnetmap, nc_policygroupmap, nc_vportmap, nc_networkmacromap, ingress_learning_acl, egress_learning_acl

    # Handling arguments
    args = get_args()
    configuration['debug'] = args.debug
    configuration['next_priority'] = args.first_priority
    configuration['log_file'] = None
    if args.logfile:
        configuration['log_file'] = args.logfile
    configuration['nuage_domain'] = args.nuage_domain
    configuration['nuage_enterprise'] = args.nuage_enterprise
    configuration['nuage_host'] = args.nuage_host
    configuration['nuage_port'] = args.nuage_port
    configuration['nuage_password'] = None
    if args.nuage_password:
        configuration['nuage_password'] = args.nuage_password
    configuration['nuage_username'] = args.nuage_username
    configuration['strictsource'] = args.strictsource
    configuration['nosslcheck'] = args.nosslcheck
    configuration['acl_type'] = args.acl_type
    configuration['verbose'] = args.verbose

    # Logging settings
    if configuration['debug']:
        log_level = logging.DEBUG
    elif configuration['verbose']:
        log_level = logging.INFO
    else:
        log_level = logging.WARNING

    logging.basicConfig(filename=configuration['log_file'],
                        format='%(asctime)s %(levelname)s %(message)s',
                        level=log_level)
    logger = logging.getLogger(__name__)

    # Disabling SSL verification if set
    if configuration['nosslcheck']:
        logger.debug('Disabling SSL certificate verification.')
        requests.packages.urllib3.disable_warnings()

    # Getting user password for Nuage connection
    if configuration['nuage_password'] is None:
        logger.debug(
            'No command line Nuage password received, requesting Nuage password from user'
        )
        configuration['nuage_password'] = getpass.getpass(
            prompt='Enter password for Nuage host %s for user %s: ' %
            (configuration['nuage_host'], configuration['nuage_username']))

    try:
        # Connecting to Nuage
        logger.info('Connecting to Nuage server %s:%s with username %s' %
                    (configuration['nuage_host'], configuration['nuage_port'],
                     configuration['nuage_username']))
        nc = vsdk.NUVSDSession(
            username=configuration['nuage_username'],
            password=configuration['nuage_password'],
            enterprise=configuration['nuage_enterprise'],
            api_url="https://%s:%s" %
            (configuration['nuage_host'], configuration['nuage_port']))
        nc.start()

    except Exception, e:
        logger.error(
            'Could not connect to Nuage host %s with user %s and specified password'
            % (configuration['nuage_host'], configuration['nuage_username']))
        logger.critical('Caught exception: %s' % str(e))
        return 1
コード例 #16
0
def main():
    """
    Main function to handle vcenter vm names and the mapping to a policy group
    """

    # Handling arguments
    args                = get_args()
    debug               = args.debug
    extended            = args.extended
    json_output         = args.json_output
    log_file            = None
    if args.logfile:
        log_file        = args.logfile
    nuage_enterprise    = args.nuage_enterprise
    nuage_host          = args.nuage_host
    nuage_port          = args.nuage_port
    nuage_password      = None
    if args.nuage_password:
        nuage_password  = args.nuage_password
    nuage_username      = args.nuage_username
    nosslcheck          = args.nosslcheck
    time_difference     = args.time_difference
    verbose             = args.verbose

    # Logging settings
    if debug:
        log_level = logging.DEBUG
    elif verbose:
        log_level = logging.INFO
    else:
        log_level = logging.WARNING

    logging.basicConfig(filename=log_file, format='%(asctime)s %(levelname)s %(message)s', level=log_level)
    logger = logging.getLogger(__name__)

    # Validating time_difference input
    time_check = re.compile('^([0-9]+)([m|h|d]?)$')
    time_matches = time_check.match(time_difference)
    if time_matches is None:
        logger.critical('The time indication %s is an invalid value, exiting' % time_difference)
        return 1

    time_diff = int(float(time_matches.group(1)))
    if time_matches.group(2) == 'm':
        logger.debug('Found m in the time difference, multiplying integer by 60')
        time_diff *= 60
    elif time_matches.group(2) == 'h':
        logger.debug('Found h in the time difference, multiplying integer by 3600')
        time_diff *= 3600
    elif time_matches.group(2) == 'd':
        logger.debug('Found d in the time difference, multiplying integer by 86400')
        time_diff *= 86400

    logger.debug('Time difference set to %s seconds' % time_diff)

    # Disabling SSL verification if set
    if nosslcheck:
        logger.debug('Disabling SSL certificate verification.')
        requests.packages.urllib3.disable_warnings()

    # Getting user password for Nuage connection
    if nuage_password is None:
        logger.debug('No command line Nuage password received, requesting Nuage password from user')
        nuage_password = getpass.getpass(prompt='Enter password for Nuage host %s for user %s: ' % (nuage_host, nuage_username))

    try:
        # Connecting to Nuage
        logger.info('Connecting to Nuage server %s:%s with username %s' % (nuage_host, nuage_port, nuage_username))
        nc = vsdk.NUVSDSession(username=nuage_username, password=nuage_password, enterprise=nuage_enterprise, api_url="https://%s:%s" % (nuage_host, nuage_port))
        nc.start()

    except Exception, e:
        logger.error('Could not connect to Nuage host %s with user %s and specified password' % (nuage_host, nuage_username))
        logger.critical('Caught exception: %s' % str(e))
        return 1
コード例 #17
0
def main():
    """
    Main function to handle statistics
    """

    # Handling arguments
    args = get_args()
    debug = args.debug
    log_file = None
    if args.logfile:
        log_file = args.logfile
    nuage_enterprise = args.nuage_enterprise
    nuage_host = args.nuage_host
    nuage_port = args.nuage_port
    nuage_password = None
    if args.nuage_password:
        nuage_password = args.nuage_password
    nuage_username = args.nuage_username
    nosslcheck = args.nosslcheck
    verbose = args.verbose
    external = args.external
    ips = []
    if args.ips:
        ips = args.ips
    macs = args.macs
    name = args.name
    subnets = args.subnets
    uuid = args.uuid

    # Logging settings
    if debug:
        log_level = logging.DEBUG
    elif verbose:
        log_level = logging.INFO
    else:
        log_level = logging.WARNING

    logging.basicConfig(filename=log_file, format='%(asctime)s %(levelname)s %(message)s', level=log_level)
    logger = logging.getLogger(__name__)

    # Sanity checks
    if len(macs) > 0 and len(macs) != len(subnets):
        logger.critical('The amount of macs is not equal to the amount of subnets, which is an invalid configuration.')
        return 1

    if len(ips) > 0 and len(macs) != len(ips):
        logger.critical('Some IPs are specified, but not the same amount as macs and subnets, which is an invalid configuration.')
        return 1

    if nosslcheck:
        logger.debug('Disabling SSL certificate verification.')
        requests.packages.urllib3.disable_warnings()

    # Getting user password for Nuage connection
    if nuage_password is None:
        logger.debug('No command line Nuage password received, requesting Nuage password from user')
        nuage_password = getpass.getpass(prompt='Enter password for Nuage host %s for user %s: ' % (nuage_host, nuage_username))

    try:
        # Connecting to Nuage
        logger.info('Connecting to Nuage server %s:%s with username %s' % (nuage_host, nuage_port, nuage_username))
        nc = vsdk.NUVSDSession(username=nuage_username, password=nuage_password, enterprise=nuage_enterprise, api_url="https://%s:%s" % (nuage_host, nuage_port))
        nc.start()

    except Exception as e:
        logger.error('Could not connect to Nuage host %s with user %s and specified password' % (nuage_host, nuage_username))
        logger.critical('Caught exception: %s' % str(e))
        return 1

    # Handling each mac/subnet combination and creating the necessary vPorts and VM Interfaces
    vports = []
    vm_interfaces = []
    for mac in macs:
        index = macs.index(mac)
        subnet_id = subnets[index]
        logger.info('Handling mac address %s connection to subnet or L2 domain %s' % (mac, subnet_id))

        logger.debug('Trying to fetch subnet for ID %s' % subnet_id)
        try:
            subnet = vsdk.NUSubnet(id=subnet_id)
            subnet.fetch()
        except:
            logger.debug('Subnet with ID %s does not exist, looking for a L2 domain' % subnet_id)
            try:
                subnet = vsdk.NUL2Domain(id=subnet_id)
                subnet.fetch()
            except:
                logger.error('Subnet with ID %s can not be found as an subnet in an L3 domain or as an L2 domain, skipping mac %s and subnet %s and continuing to the next pair' % (subnet_id, mac, subnet_id))
                continue

        # Creating vPort in subnet
        logger.debug('Creating vPort %s-vPort-%s in subnet %s (%s)' % (name, index, subnet.name, subnet_id))
        vport = vsdk.NUVPort(name='%s-vPort-%s' % (name, index), address_spoofing='INHERITED', type='VM', description='Automatically created, do not edit.')
        if external:
            vport.external_id = '%s-vPort-%s' % (name, index)
        subnet.create_child(vport)
        vports.append(vport)

        # Creating VMInterface
        logger.debug('Creating VMInterface object %s-vm-interface-%s for mac %s with vPort ID %s' % (name, index, mac, vport.id))
        vm_interface = vsdk.NUVMInterface(name='%s-vm-interface-%s' % (name, index), vport_id=vport.id, mac=mac)
        if external:
            vm_interface.external_id = '%s-vm-interface-%s' % (name, index)
        if len(ips) > 0:
            vm_interface.ip_address = ips[index]
        vm_interfaces.append(vm_interface)

    # Creating VM
    logger.info('Creating VM %s with UUID %s' % (name, uuid))
    vm = vsdk.NUVM(name=name, uuid=uuid, interfaces=vm_interfaces)
    if external:
        vm.external_id = uuid
    try:
        logger.debug('Trying to save VM %s.' % name)
        nc.user.create_child(vm)
    except Exception as e:
        logger.critical('VM %s can not be created because of error %s' % (name, str(e)))
        logger.debug('Cleaning up the vPorts')
        for vport in vports:
            logger.debug('Deleting vPort %s' % vport.name)
            vport.delete()
        return 1

    logger.info('Created all necessary entities in the appropriate subnets or L2 domains for VM %s' % name)
    return 0
コード例 #18
0
def main():
    """
    Manage the vCenter Integration Node configuration
    """

    # Handling arguments
    args = get_args()
    debug = args.debug
    folder_name = None
    if args.folder:
        folder_name = args.folder
    log_file = None
    if args.logfile:
        log_file = args.logfile
    name = args.name
    nuage_enterprise = args.nuage_enterprise
    nuage_host = args.nuage_host
    nuage_port = args.nuage_port
    nuage_password = None
    if args.nuage_password:
        nuage_password = args.nuage_password
    nuage_username = args.nuage_username
    nuage_vm_enterprise = None
    if args.nuage_vm_enterprise:
        nuage_vm_enterprise = args.nuage_vm_enterprise
    nuage_vm_domain = None
    if args.nuage_vm_domain:
        nuage_vm_domain = args.nuage_vm_domain
    nuage_vm_zone = None
    if args.nuage_vm_zone:
        nuage_vm_zone = args.nuage_vm_zone
    nuage_vm_subnet = None
    if args.nuage_vm_subnet:
        nuage_vm_subnet = args.nuage_vm_subnet
    nuage_vm_ip = None
    if args.nuage_vm_ip:
        nuage_vm_ip = args.nuage_vm_ip
    nuage_vm_user = None
    if args.nuage_vm_user:
        nuage_vm_user = args.nuage_vm_user
    power_on = not args.nopoweron
    resource_pool_name = None
    if args.resource_pool:
        resource_pool_name = args.resource_pool
    nosslcheck = args.nosslcheck
    template = args.template
    vcenter_host = args.vcenter_host
    vcenter_port = args.vcenter_port
    vcenter_password = None
    if args.vcenter_password:
        vcenter_password = args.vcenter_password
    vcenter_username = args.vcenter_username
    verbose = args.verbose

    # Logging settings
    if debug:
        log_level = logging.DEBUG
    elif verbose:
        log_level = logging.INFO
    else:
        log_level = logging.WARNING

    logging.basicConfig(filename=log_file,
                        format='%(asctime)s %(levelname)s %(message)s',
                        level=log_level)
    logger = logging.getLogger(__name__)

    # Disabling SSL verification if set
    ssl_context = None
    if nosslcheck:
        logger.debug('Disabling SSL certificate verification.')
        requests.packages.urllib3.disable_warnings()
        import ssl
        if hasattr(ssl, 'SSLContext'):
            ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
            ssl_context.verify_mode = ssl.CERT_NONE

    # Getting user password for Nuage connection
    if nuage_password is None:
        logger.debug(
            'No command line Nuage password received, requesting Nuage password from user'
        )
        nuage_password = getpass.getpass(
            prompt='Enter password for Nuage host %s for user %s: ' %
            (nuage_host, nuage_username))

    # Getting user password for vCenter connection
    if vcenter_password is None:
        logger.debug(
            'No command line vCenter password received, requesting vCenter password from user'
        )
        vcenter_password = getpass.getpass(
            prompt='Enter password for vCenter host %s for user %s: ' %
            (vcenter_host, vcenter_username))

    try:
        vc = None
        nc = None

        # Connecting to Nuage
        try:
            logger.info('Connecting to Nuage server %s:%s with username %s' %
                        (nuage_host, nuage_port, nuage_username))
            nc = vsdk.NUVSDSession(username=nuage_username,
                                   password=nuage_password,
                                   enterprise=nuage_enterprise,
                                   api_url="https://%s:%s" %
                                   (nuage_host, nuage_port))
            nc.start()
        except IOError, e:
            pass

        if not nc or not nc.is_current_session():
            logger.error(
                'Could not connect to Nuage host %s with user %s, enterprise %s and specified password'
                % (nuage_host, nuage_username, nuage_enterprise))
            return 1

        # Connecting to vCenter
        try:
            logger.info('Connecting to vCenter server %s:%s with username %s' %
                        (vcenter_host, vcenter_port, vcenter_username))
            if ssl_context:
                vc = SmartConnect(host=vcenter_host,
                                  user=vcenter_username,
                                  pwd=vcenter_password,
                                  port=int(vcenter_port),
                                  sslContext=ssl_context)
            else:
                vc = SmartConnect(host=vcenter_host,
                                  user=vcenter_username,
                                  pwd=vcenter_password,
                                  port=int(vcenter_port))
        except IOError, e:
            pass
コード例 #19
0
def main():

    #############################################
    # create a new session
    #############################################
    session = vspk.NUVSDSession(username=username,
                                password=password,
                                enterprise=enterprise,
                                api_url=api_url)
    # start the session.
    try:
        session.start()
    except:
        print('ERROR: Failed to start the session')

    csprootSession = session.user

    ###########################################
    #  Create and Assign User to root group   #
    ###########################################
    func_create_users(session, userName1, userEmail)
    func_create_users(session, userName2, userEmail)

    #############################################
    # create VNS infrastructure - NSG profile
    #############################################
    infrastructure_gw_profile = func_create_infr_gw_profiles(csprootSession)

    #############################################
    # create two  VSC profile(s)
    #############################################
    infrastructure_vsc_profile1 = func_create_infr_vsc_profiles(
        csprootSession, infrVsc1Name, VSC1_IP)
    infrastructure_vsc_profile2 = func_create_infr_vsc_profiles(
        csprootSession, infrVsc2Name, VSC2_IP)

    #############################################
    # create VNS infrastructure - Access profile
    #############################################
    infra_access_profile = func_create_infr_access_profiles(
        csprootSession, infrAccessName, infrAccessUserName, infrAccessPassword)

    ######################################################
    # create 3 NSG templates (1WAN_1LAN, 2WAN_2LAN, 2WAN_4LAN)
    ######################################################
    nsgtemplate_2w_1l = func_create_nsg_2w_1l_template(
        csprootSession, nsgTemplate1Name, infrastructure_gw_profile,
        infra_access_profile, infrastructure_vsc_profile1,
        infrastructure_vsc_profile2)

    nsgtemplate_2w_2l = func_create_nsg_2w_2l_template(
        csprootSession, nsgTemplate2Name, infrastructure_gw_profile,
        infra_access_profile, infrastructure_vsc_profile1,
        infrastructure_vsc_profile2)

    nsgtemplate_2w_4l = func_create_nsg_2w_4l_template(
        csprootSession, nsgTemplate3Name, infrastructure_gw_profile,
        infra_access_profile, infrastructure_vsc_profile1,
        infrastructure_vsc_profile2)

    ###########################################
    # Creating Advanced Organization Profile  #
    ###########################################
    infrastructure_org_profile = func_create_infr_org_profiles(
        csprootSession, infrOrganizationProfileName)

    ###########################################
    # Enable the VSS Flow collection flag in the system configuration
    ###########################################
    func_enable_vss_flow_collection(session)

    #############################################
    # create a new Enterprise
    #############################################
    new_enterprise = func_create_enterprise(csprootSession, enterpriseName,
                                            enterpriseLocalAS,
                                            infrastructure_org_profile)

    #############################################
    # create a new Enterprise User admin and assign him to group admin
    #############################################
    func_create_ent_users(csprootSession, userEntName1, userEmail,
                          enterpriseName)

    #############################################
    # create a new Domain template for branch (encr) and DC (non-encry)
    #############################################
    # create a new Domain template; one for branch and one for dc
    new_br_domain_template = func_create_l3domain_template(new_enterprise,
                                                           brdomainTemplate,
                                                           branchordc='branch')
    new_dc_domain_template = func_create_l3domain_template(new_enterprise,
                                                           dcdomainTemplate,
                                                           branchordc='dc')

    #############################################
    # create a new Branch Domain, Zones, Subnets
    #############################################
    # create a new branch encrypted Domain
    domdescription = 'Encrypted domain'
    natflag = 'ENABLED'
    domencryption = 'ENABLED'
    new_br_domain = func_create_l3domain(new_br_domain_template, brdomainName,
                                         new_enterprise, domdescription,
                                         natflag, domencryption, domainDNS)

    # create a new branch Zones
    new_zone1 = func_create_zone(csprootSession, new_br_domain, zone1Name,
                                 zone1Description)
    new_zone2 = func_create_zone(csprootSession, new_br_domain, zone2Name,
                                 zone2Description)
    new_zone3 = func_create_zone(csprootSession, new_br_domain, zone3Name,
                                 zone3Description)

    # create a new subnets
    subnet1_zone1 = func_create_subnet(csprootSession, new_zone1, subnet1Name,
                                       zone1Description, subnet1IpAddr,
                                       subnet1Prefix, subnet1DhcpMinRange,
                                       subnet1DhcpMaxRange)
    subnet2_zone1 = func_create_subnet(csprootSession, new_zone1, subnet2Name,
                                       zone1Description, subnet2IpAddr,
                                       subnet2Prefix, subnet2DhcpMinRange,
                                       subnet2DhcpMaxRange)
    subnet1_zone2 = func_create_subnet(csprootSession, new_zone2, subnet3Name,
                                       zone2Description, subnet3IpAddr,
                                       subnet3Prefix, subnet3DhcpMinRange,
                                       subnet3DhcpMaxRange)
    subnet1_zone3 = func_create_subnet(csprootSession, new_zone3, subnet4Name,
                                       zone3Description, subnet4IpAddr,
                                       subnet4Prefix, subnet4DhcpMinRange,
                                       subnet4DhcpMaxRange)
    subnet2_zone3 = func_create_subnet(csprootSession, new_zone3, subnet5Name,
                                       zone3Description, subnet5IpAddr,
                                       subnet5Prefix, subnet5DhcpMinRange,
                                       subnet5DhcpMaxRange)

    #############################################
    # create a new "DC" Domain, Zones, Subnets
    #############################################
    # create a new DC non-encrypted Domain
    domdescription = 'No Encryption domain'
    natflag = 'ENABLED'
    domencryption = 'DISABLED'
    new_dc_domain = func_create_l3domain(new_dc_domain_template, dcdomainName,
                                         new_enterprise, domdescription,
                                         natflag, domencryption, domainDNS)
    # create a new branch Zones
    new_dc_zone1 = func_create_zone(csprootSession, new_dc_domain, dczone1Name,
                                    dczone1Description)
    # create a new subnets
    dc_subnet1_zone1 = func_create_subnet(csprootSession, new_dc_zone1,
                                          dcsubnet1Name, dczone1Description,
                                          dcsubnet1IpAddr, dcsubnet1Prefix,
                                          dcsubnet1DhcpMinRange,
                                          dcsubnet1DhcpMaxRange)
    dc_subnet2_zone1 = func_create_subnet(csprootSession, new_dc_zone1,
                                          dcsubnet2Name, dczone1Description,
                                          dcsubnet2IpAddr, dcsubnet2Prefix,
                                          dcsubnet2DhcpMinRange,
                                          dcsubnet2DhcpMaxRange)
    dc_subnet3_zone1 = func_create_subnet(csprootSession, new_dc_zone1,
                                          dcsubnet3Name, dczone1Description,
                                          dcsubnet3IpAddr, dcsubnet3Prefix,
                                          dcsubnet3DhcpMinRange,
                                          dcsubnet3DhcpMaxRange)
    dc_subnet4_zone1 = func_create_subnet(csprootSession, new_dc_zone1,
                                          dcsubnet4Name, dczone1Description,
                                          dcsubnet4IpAddr, dcsubnet4Prefix,
                                          dcsubnet4DhcpMinRange,
                                          dcsubnet4DhcpMaxRange)

    #############################################
    # create 3 New NSGs Instances; one from each template
    #############################################
    func_create_nsg(new_enterprise, nsgtemplate_2w_1l, NSGName1)
    func_create_nsg(new_enterprise, nsgtemplate_2w_1l, NSGName2)
    func_create_nsg(new_enterprise, nsgtemplate_2w_1l, NSGName3)
    func_create_nsg(new_enterprise, nsgtemplate_2w_1l, NSGName4)