Put the DNS into the ssh config file.
974647
def update_ssh_config(self, path="~/.ssh/config"):
        """"""
        # Read the config file #
        import sshconf
        config = sshconf.read_ssh_config(os.path.expanduser(path))
        # In case it doesn't exist #
        if not config.host(self.instance_name): config.add(self.instance_name)
        # Add the new DNS #
        config.set(self.instance_name, Hostname=self.dns)
        # Write result #
        config.write(os.path.expanduser(path))
871215
def _setup_ssh(self):
        """"""
        global paramiko
        if paramiko is none:
            import paramiko

        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(self.server, username=self.user, pkey=self.pkey)
638104
def put_httpsconf(self, name, certid, forceHttps):
        
        req = {}
        req.update({"certid": certid})
        req.update({"forceHttps": forceHttps})

        body = json.dumps(req)
        url = '{0}/domain/{1}/httpsconf'.format(self.server, name)
        return self.__put(url, body)
158246
def establish_ssh(target=None, auto_trust=False, allow_agent=True, look_keys=True):
    
    '''

    def password_prompt(username, hostname):
        r'''
        If the Host is relying on password authentication, lets ask it.
        Relying on SSH itself to take care of that would not work when the
        remote authentication is password behind a SSH-key+2FA jumphost.
        '''
        return getpass.getpass('No SSH key for %s@%s, please provide password: ' % (username, hostname))

    ssh_conn = None
    if target is not None:
        ssh_conf = get_sshconfig()
        cfg = {
            'hostname': None,
            'port': 22,
            'allow_agent': allow_agent,
            'look_for_keys': look_keys
        }
        if ssh_conf.has_key(target):
            user_config = ssh_conf.get(target)

            # If ssh_config file's Host defined 'User' instead of 'Username'
            if user_config.has_key('user') and not user_config.has_key('username'):
                user_config['username'] = user_config['user']
                del user_config['user']

            for k in ('username', 'hostname', 'port'):
                if k in user_config:
                    cfg[k] = user_config[k]

            # Assume Password auth. If we don't do that, then when connecting
            # through a jumphost we will run into issues and the user will
            # not be able to input his password to the SSH prompt.
            if 'identityfile' in user_config:
                cfg['key_filename'] = user_config['identityfile']
            else:
                cfg['password'] = password_prompt(cfg['username'], cfg['hostname'] or target)

            # Should be the last one, since ProxyCommand will issue connection to remote host
            if 'proxycommand' in user_config:
                cfg['sock'] = paramiko.ProxyCommand(user_config['proxycommand'])

        else:
            cfg['username'] = target.split('@')[0]
            cfg['hostname'] = target.split('@')[1].split(':')[0]
            cfg['password'] = password_prompt(cfg['username'], cfg['hostname'])
            try:
                cfg['port'] = int(target.split('@')[1].split(':')[1])
            except IndexError:
                # IndexError will happen if no :PORT is there.
                # Default value 22 is defined above in 'cfg'.
                pass

        ssh_conn = paramiko.SSHClient()
        if auto_trust:
            ssh_conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        ssh_conn.connect(**cfg)

    return ssh_conn
1303612
def install(self):
        
        domain_settings = DomainSettings.get()

        with root():
            if os.path.exists(self.SMBCONF_FILE):
                os.remove(self.SMBCONF_FILE)

            if domain_settings.mode == 'ad':
                domain_settings.adminpass = make_password(15)
                domain_settings.save()

                run("samba-tool domain provision "
                    "--domain='%s' "
                    "--workgroup='%s' "
                    "--realm='%s' "
                    "--use-xattrs=yes "
                    "--use-rfc2307 "
                    "--server-role='domain controller' "
                    "--use-ntvfs "
                    "--adminpass='%s'" %
                    (domain_settings.domain,
                     domain_settings.workgroup,
                     domain_settings.realm,
                     domain_settings.adminpass))

                self.smbconf.write()

                shutil.copy2(self.SMB_KRB5CONF_FILE, self.KRB5CONF_FILE)

                # XXX FIXME move this to network
                run("echo 'nameserver 127.0.0.1' > /etc/resolv.conf")
                # TODO manage shares
                run("touch /etc/samba/shares.conf")

            elif domain_settings.mode == 'member':
                # TODO
                pass
536735
def add_hostname_cn_ip(self, addresses):
        
        for addr in addresses:
            if addr not in self.hostname_entry['addresses']:
                self.hostname_entry['addresses'].append(addr)
775608
def add_host(ip, alias):
    '''
    
    '''
    hfn = _get_or_create_hostfile()
    if not os.path.isfile(hfn):
        return False

    if has_pair(ip, alias):
        return True

    hosts = _list_hosts()

    # Make sure future calls to _list_hosts() will re-read the file
    __context__.pop('hosts._list_hosts', None)

    inserted = False
    for i, h in six.iteritems(hosts):
        for j in range(len(h)):
            if h[j].startswith('#') and i == ip:
                h.insert(j, alias)
                inserted = True
    if not inserted:
        hosts.setdefault(ip, []).append(alias)
    _write_hosts(hosts)
    return True
854841
def clone(self):
        
        self.config['hostname'] = self.config['hostname'].lower()
        self.config['mem'] = int(self.config['mem'] * 1024)  # convert GB to MB

        print("Cloning %s to new host %s with %sMB RAM..." % (
            self.config['template'],
            self.config['hostname'],
            self.config['mem']
        ))

        # initialize a list to hold our network settings
        ip_settings = list()

        # Get network settings for each IP
        for key, ip_string in enumerate(self.config['ips']):

            # convert ip from string to the 'IPAddress' type
            ip = IPAddress(ip_string)

            # determine network this IP is in
            for network in self.config['networks']:
                if ip in IPNetwork(network):
                    self.config['networks'][network]['ip'] = ip
                    ipnet = IPNetwork(network)
                    self.config['networks'][network]['subnet_mask'] = str(
                        ipnet.netmask
                    )
                    ip_settings.append(self.config['networks'][network])

            # throw an error if we couldn't find a network for this ip
            if not any(d['ip'] == ip for d in ip_settings):
                print("I don't know what network %s is in.  You can supply "
                      "settings for this network in config.yml." % ip_string)
                sys.exit(1)

        # network to place new VM in
        self.get_obj([vim.Network], ip_settings[0]['network'])
        datacenter = self.get_obj([vim.Datacenter],
                                  ip_settings[0]['datacenter']
                                  )

        # get the folder where VMs are kept for this datacenter
        if self.config['destination_folder']:
            destfolder = self.content.searchIndex.FindByInventoryPath(
                self.config['destination_folder']
            )
        else:
            destfolder = datacenter.vmFolder

        cluster = self.get_obj([vim.ClusterComputeResource],
                               ip_settings[0]['cluster']
                               )

        resource_pool_str = self.config['resource_pool']
        # resource_pool setting in config file takes priority over the
        # default 'Resources' pool
        if resource_pool_str == 'Resources' \
                and ('resource_pool' in ip_settings[key]):
            resource_pool_str = ip_settings[key]['resource_pool']

        resource_pool = self.get_resource_pool(cluster, resource_pool_str)

        host_system = self.config['host']
        if host_system != "":
            host_system = self.get_obj([vim.HostSystem],
                                       self.config['host']
                                       )

        if self.debug:
            self.print_debug(
                "Destination cluster",
                cluster
            )
            self.print_debug(
                "Resource pool",
                resource_pool
            )

        if resource_pool is None:
            # use default resource pool of target cluster
            resource_pool = cluster.resourcePool

        datastore = None

        if self.config['datastore']:
            datastore = self.get_obj(
                [vim.Datastore], self.config['datastore'])
        elif 'datastore' in ip_settings[0]:
            datastore = self.get_obj(
                [vim.Datastore],
                ip_settings[0]['datastore'])
        if datastore is None:
            print("Error: Unable to find Datastore '%s'"
                  % ip_settings[0]['datastore'])
            sys.exit(1)

        if self.config['template_folder']:
            template_vm = self.get_vm_failfast(
                self.config['template'],
                False,
                'Template VM',
                path=self.config['template_folder']
            )
        else:
            template_vm = self.get_vm_failfast(
                self.config['template'],
                False,
                'Template VM'
            )

        # Relocation spec
        relospec = vim.vm.RelocateSpec()
        relospec.datastore = datastore
        if host_system:
            relospec.host = host_system

        if resource_pool:
            relospec.pool = resource_pool

        # Networking self.config for VM and guest OS
        devices = []
        adaptermaps = []

        # add existing NIC devices from template to our list of NICs
        # to be created
        try:
            for device in template_vm.config.hardware.device:

                if hasattr(device, 'addressType'):
                    # this is a VirtualEthernetCard, so we'll delete it
                    nic = vim.vm.device.VirtualDeviceSpec()
                    nic.operation = \
                        vim.vm.device.VirtualDeviceSpec.Operation.remove
                    nic.device = device
                    devices.append(nic)
        except:
            # not the most graceful handling, but unable to reproduce
            # user's issues in #57 at this time.
            pass

        # create a Network device for each static IP
        for key, ip in enumerate(ip_settings):
            # VM device
            nic = vim.vm.device.VirtualDeviceSpec()
            # or edit if a device exists
            nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
            nic.device = vim.vm.device.VirtualVmxnet3()
            nic.device.wakeOnLanEnabled = True
            nic.device.addressType = 'assigned'
            # 4000 seems to be the value to use for a vmxnet3 device
            nic.device.key = 4000
            nic.device.deviceInfo = vim.Description()
            nic.device.deviceInfo.label = 'Network Adapter %s' % (key + 1)
            if 'dvportgroup' in ip_settings[key]:
                dvpg = ip_settings[key]['dvportgroup']
                nic.device.deviceInfo.summary = dvpg
                pg_obj = self.get_obj([vim.dvs.DistributedVirtualPortgroup], dvpg)  # noqa
                dvs_port_connection = vim.dvs.PortConnection()
                dvs_port_connection.portgroupKey = pg_obj.key
                dvs_port_connection.switchUuid = (
                    pg_obj.config.distributedVirtualSwitch.uuid
                )
                # did it to get pep8
                e_nic = vim.vm.device.VirtualEthernetCard
                nic.device.backing = (
                    e_nic.DistributedVirtualPortBackingInfo()
                )

                nic.device.backing.port = dvs_port_connection
            else:
                nic.device.deviceInfo.summary = ip_settings[key]['network']
                nic.device.backing = (
                    vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
                )
                nic.device.backing.network = (
                    self.get_obj([vim.Network], ip_settings[key]['network'])
                )
                nic.device.backing.deviceName = ip_settings[key]['network']
                nic.device.backing.useAutoDetect = False

            nic.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
            nic.device.connectable.startConnected = True
            nic.device.connectable.allowGuestControl = True
            devices.append(nic)

            if 'customspecname' in ip_settings[key]:
                custom_spec_name = ip_settings[key]['customspecname']
                customspec = (
                    self.get_customization_settings(custom_spec_name)
                )
                guest_map = customspec.nicSettingMap[0]
            else:
                customspec = vim.vm.customization.Specification()
                # guest NIC settings, i.e. 'adapter map'
                guest_map = vim.vm.customization.AdapterMapping()
                guest_map.adapter = vim.vm.customization.IPSettings()
            guest_map.adapter.ip = vim.vm.customization.FixedIp()
            guest_map.adapter.ip.ipAddress = str(ip_settings[key]['ip'])

            if 'subnet_mask' in ip_settings[key]:
                guest_map.adapter.subnetMask = (
                    str(ip_settings[key]['subnet_mask'])
                )

            if 'gateway' in ip_settings[key]:
                guest_map.adapter.gateway = ip_settings[key]['gateway']

            if self.config['domain']:
                guest_map.adapter.dnsDomain = self.config['domain']

            adaptermaps.append(guest_map)

        # DNS settings
        if 'dns_servers' in self.config:
            globalip = vim.vm.customization.GlobalIPSettings()
            globalip.dnsServerList = self.config['dns_servers']
            globalip.dnsSuffixList = self.config['domain']
            customspec.globalIPSettings = globalip

        # Hostname settings
        ident = vim.vm.customization.LinuxPrep()
        ident.domain = self.config['domain']
        ident.hostName = vim.vm.customization.FixedName()
        ident.hostName.name = self.config['hostname']

        customspec.nicSettingMap = adaptermaps
        customspec.identity = ident

        # VM config spec
        vmconf = vim.vm.ConfigSpec()
        vmconf.numCPUs = self.config['cpus']
        vmconf.memoryMB = self.config['mem']
        vmconf.cpuHotAddEnabled = True
        vmconf.memoryHotAddEnabled = True
        vmconf.deviceChange = devices

        # Clone spec
        clonespec = vim.vm.CloneSpec()
        clonespec.location = relospec
        clonespec.config = vmconf
        clonespec.customization = customspec
        clonespec.powerOn = True
        clonespec.template = False

        self.addDisks(template_vm, clonespec)

        if self.debug:
            self.print_debug("CloneSpec", clonespec)

        # fire the clone task
        tasks = [template_vm.Clone(folder=destfolder,
                                   name=self.config['hostname'],
                                   spec=clonespec
                                   )]
        result = self.WaitForTasks(tasks)

        if self.config['post_clone_cmd']:
            try:
                # helper env variables
                os.environ['EZMOMI_CLONE_HOSTNAME'] = self.config['hostname']
                print("Running --post-clone-cmd %s"
                      % self.config['post_clone_cmd'])
                os.system(self.config['post_clone_cmd'])

            except Exception as e:
                print("Error running post-clone command. Exception: %s" % e)
                pass

        # send notification email
        if self.config['mail']:
            self.send_email()
1181233
def launch_ssh(self, name, port):
        """"""
        if options.user:
            name = '%s@%s' % (options.user, name)
        evaluated = options.ssh % {'host': name, 'port': port}
        if evaluated == options.ssh:
            evaluated = '%s %s' % (evaluated, name)
        os.execlp('/bin/sh', 'sh', '-c', evaluated)
67688
def UpdateDNS(self, domain, environment):
        """"""
        self.dns_set_conf(domain, self.dns.config,
                          environment, self.dns.token)
453386
def _set_hostname_domain(self):
        """"""
        self._hostname, _, self._domain = str(self._fqdn).partition('.')
        log.debug('Hostname: %s, Domain: %s' % (self._hostname, self._domain))
39718
def setup_config(command, filename, section, vars):
    """"""
    confuri = "config:" + filename
    if ":" in section:
        confuri += "#" + section.rsplit(":", 1)[-1]
    conf = appconfig(confuri)

    load_environment(conf.global_conf, conf.local_conf)
488584
def _request_add_dns_record(self, record):
        """"""
        return self._request_internal("Add_DNS_Record",
                                      domain=self.domain,
                                      record=record)
371416
def post(self, *args, **kwargs):
        """"""

        existing_ssh = models.SSHConfig.objects.all()

        if existing_ssh.exists():
            return self.get_view()

        remote_user = self.request.POST.get('remote_user', 'root')

        create_ssh_config(remote_user=remote_user)

        return self.get_view()
902445
def add_dnsbl(name,domain,type='ip',codes={"0"=>"OK","127.0.0.2"=>"Blacklisted"})
			@dnsbls[name] = codes
			@dnsbls[name]['domain'] = domain
			@dnsbls[name]['type'] = type
		end
599716
def cli(env):
    """"""

    username, secret, endpoint_url, timeout = get_user_input(env)
    new_client = SoftLayer.Client(username=username, api_key=secret, endpoint_url=endpoint_url, timeout=timeout)
    api_key = get_api_key(new_client, username, secret)

    path = '~/.softlayer'
    if env.config_file:
        path = env.config_file
    config_path = os.path.expanduser(path)

    env.out(env.fmt(config.config_table({'username': username,
                                         'api_key': api_key,
                                         'endpoint_url': endpoint_url,
                                         'timeout': timeout})))

    if not formatting.confirm('Are you sure you want to write settings '
                              'to "%s"?' % config_path, default=True):
        raise exceptions.CLIAbort('Aborted.')

    # Persist the config file. Read the target config file in before
    # setting the values to avoid clobbering settings
    parsed_config = utils.configparser.RawConfigParser()
    parsed_config.read(config_path)
    try:
        parsed_config.add_section('softlayer')
    except utils.configparser.DuplicateSectionError:
        pass

    parsed_config.set('softlayer', 'username', username)
    parsed_config.set('softlayer', 'api_key', api_key)
    parsed_config.set('softlayer', 'endpoint_url', endpoint_url)
    parsed_config.set('softlayer', 'timeout', timeout)

    config_fd = os.fdopen(os.open(config_path,
                                  (os.O_WRONLY | os.O_CREAT | os.O_TRUNC),
                                  0o600),
                          'w')
    try:
        parsed_config.write(config_fd)
    finally:
        config_fd.close()

    env.fout("Configuration Updated Successfully")
684562
def add(name, connection_uri, id_file="", o=[], config=None):
    
    storm_ = get_storm_instance(config)

    try:

        # validate name
        if '@' in name:
            raise ValueError('invalid value: "@" cannot be used in name.')

        user, host, port = parse(
            connection_uri,
            user=get_default("user", storm_.defaults),
            port=get_default("port", storm_.defaults)
        )

        storm_.add_entry(name, host, user, port, id_file, o)

        print(
            get_formatted_message(
                '{0} added to your ssh config. you can connect '
                'it by typing "ssh {0}".'.format(name),
            'success')
        )

    except ValueError as error:
        print(get_formatted_message(error, 'error'), file=sys.stderr)
        sys.exit(1)