Get all host names matching the pattern
178542
def _hosts_in_unenumerated_pattern(self, pattern):
        

        hosts = {}
        # ignore any negative checks here, this is handled elsewhere
        pattern = pattern.replace("!","").replace("&", "")

        groups = self.get_groups()
        for group in groups:
            for host in group.get_hosts():
                if pattern == 'all' or self._match(group.name, pattern) or self._match(host.name, pattern):
                    hosts[host.name] = host
        return sorted(hosts.values(), key=lambda x: x.name)
1189544
def to_hostnames_list(ref, tab):  # pragma: no cover, to be deprecated?
    
    res = []
    for host in tab:
        if hasattr(host, 'host_name'):
            res.append(host.host_name)
    return res
280730
def DbGetHostList(self, argin):
        
        self._log.debug("In DbGetHostList()")
        argin = replace_wildcard(argin)
        return self.db.get_host_list(argin)
414638
def GetClientURNsForHostnames(hostnames, token=None):
  

  if data_store.RelationalDBEnabled():
    index = ClientIndex()
  else:
    index = CreateClientIndex(token=token)

  keywords = set()
  for hostname in hostnames:
    if hostname.startswith("host:"):
      keywords.add(hostname)
    else:
      keywords.add("host:%s" % hostname)
  results = index.ReadClientPostingLists(keywords)

  result = {}
  for keyword, hits in iteritems(results):
    result[keyword[len("host:"):]] = hits
  return result
136152
def get_hostname(url):
        

        if url not in URLHelper.__cache:
            URLHelper.__cache[url] = urlparse(url)

        parts = URLHelper.__cache[url].netloc.split(".")

        if len(parts) == 1:
            return parts[0]
        else:
            return ".".join(parts[-2:-1])
1292778
def _dnsname_match(dn, hostname, max_wildcards=1):
    
    pats = []
    if not dn:
        return False

    split_dn = dn.split(r'.')
    leftmost, remainder = split_dn[0], split_dn[1:]

    wildcards = leftmost.count('*')
    if wildcards > max_wildcards:
        # Issue #17980: avoid denials of service by refusing more
        # than one wildcard per fragment.  A survey of established
        # policy among SSL implementations showed it to be a
        # reasonable choice.
        raise CertificateError(
            "too many wildcards in certificate DNS name: " + repr(dn))

    # speed up common case w/o wildcards
    if not wildcards:
        return dn.lower() == hostname.lower()

    # RFC 6125, section 6.4.3, subitem 1.
    # The client SHOULD NOT attempt to match a presented identifier in which
    # the wildcard character comprises a label other than the left-most label.
    if leftmost == '*':
        # When '*' is a fragment by itself, it matches a non-empty dotless
        # fragment.
        pats.append('[^.]+')
    elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
        # RFC 6125, section 6.4.3, subitem 3.
        # The client SHOULD NOT attempt to match a presented identifier
        # where the wildcard character is embedded within an A-label or
        # U-label of an internationalized domain name.
        pats.append(re.escape(leftmost))
    else:
        # Otherwise, '*' matches any dotless string, e.g. www*
        pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))

    # add the remaining fragments, ignore any wildcards
    for frag in remainder:
        pats.append(re.escape(frag))

    pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
    return pat.match(hostname)
410998
def __get_known_node_by_host(self, hostname):
        '''
        
        '''
        for n in self.nodes:
            if (n.name == hostname):
                return n
        return None
461272
private boolean verifyHostName(String hostName, String pattern) {
    // Basic sanity checks
    // Check length == 0 instead of .isEmpty() to support Java 5.
    if ((hostName == null) || (hostName.length() == 0) || (hostName.startsWith("."))
        || (hostName.endsWith(".."))) {
      // Invalid domain name
      return false;
    }
    if ((pattern == null) || (pattern.length() == 0) || (pattern.startsWith("."))
        || (pattern.endsWith(".."))) {
      // Invalid pattern/domain name
      return false;
    }

    // Normalize hostName and pattern by turning them into absolute domain names if they are not
    // yet absolute. This is needed because server certificates do not normally contain absolute
    // names or patterns, but they should be treated as absolute. At the same time, any hostName
    // presented to this method should also be treated as absolute for the purposes of matching
    // to the server certificate.
    //   www.android.com  matches www.android.com
    //   www.android.com  matches www.android.com.
    //   www.android.com. matches www.android.com.
    //   www.android.com. matches www.android.com
    if (!hostName.endsWith(".")) {
      hostName += '.';
    }
    if (!pattern.endsWith(".")) {
      pattern += '.';
    }
    // hostName and pattern are now absolute domain names.

    pattern = pattern.toLowerCase(Locale.US);
    // hostName and pattern are now in lower case -- domain names are case-insensitive.

    if (!pattern.contains("*")) {
      // Not a wildcard pattern -- hostName and pattern must match exactly.
      return hostName.equals(pattern);
    }
    // Wildcard pattern

    // WILDCARD PATTERN RULES:
    // 1. Asterisk (*) is only permitted in the left-most domain name label and must be the
    //    only character in that label (i.e., must match the whole left-most label).
    //    For example, *.example.com is permitted, while *a.example.com, a*.example.com,
    //    a*b.example.com, a.*.example.com are not permitted.
    // 2. Asterisk (*) cannot match across domain name labels.
    //    For example, *.example.com matches test.example.com but does not match
    //    sub.test.example.com.
    // 3. Wildcard patterns for single-label domain names are not permitted.

    if ((!pattern.startsWith("*.")) || (pattern.indexOf('*', 1) != -1)) {
      // Asterisk (*) is only permitted in the left-most domain name label and must be the only
      // character in that label
      return false;
    }

    // Optimization: check whether hostName is too short to match the pattern. hostName must be at
    // least as long as the pattern because asterisk must match the whole left-most label and
    // hostName starts with a non-empty label. Thus, asterisk has to match one or more characters.
    if (hostName.length() < pattern.length()) {
      // hostName too short to match the pattern.
      return false;
    }

    if ("*.".equals(pattern)) {
      // Wildcard pattern for single-label domain name -- not permitted.
      return false;
    }

    // hostName must end with the region of pattern following the asterisk.
    String suffix = pattern.substring(1);
    if (!hostName.endsWith(suffix)) {
      // hostName does not end with the suffix
      return false;
    }

    // Check that asterisk did not match across domain name labels.
    int suffixStartIndexInHostName = hostName.length() - suffix.length();
    if ((suffixStartIndexInHostName > 0)
        && (hostName.lastIndexOf('.', suffixStartIndexInHostName - 1) != -1)) {
      // Asterisk is matching across domain name labels -- not permitted.
      return false;
    }

    // hostName matches pattern
    return true;
  }
1234821
private String[] splitHostNames(String hostNames)
    {
        String[] hostArray = hostNames.split(Constants.COMMA);
        String[] hosts = new String[hostArray.length];
        for (int i = 0; i < hostArray.length; i++)
        {
            hosts[i] = hostArray[i].trim();
        }
        return hosts;
    }
743879
def hostname_for_event(self, clean_server_name):
        """"""
        uri = urlsplit(clean_server_name)
        if '@' in uri.netloc:
            hostname = uri.netloc.split('@')[1].split(':')[0]
        else:
            hostname = uri.netloc.split(':')[0]
        if hostname == 'localhost':
            hostname = self.hostname
        return hostname
1179133
def parseSLURM(string):
    """"""
    # Use scontrol utility to get the hosts list
    import subprocess, os
    hostsstr = subprocess.check_output(["scontrol", "show", "hostnames", string])
    if sys.version_info.major > 2:
        hostsstr = hostsstr.decode()
    # Split using endline
    hosts = hostsstr.split(os.linesep)
    # Take out last empty host
    hosts = filter(None, hosts)
    # Create the desired pair of host and number of hosts
    hosts = [(host, 1) for host in hosts]
    return hosts
322897
def get_all_names(offset=None, count=None, include_expired=False, proxy=None, hostport=None):
    
    assert proxy or hostport, 'Need proxy or hostport'
    if proxy is None:
        proxy = connect_hostport(hostport)

    offset = 0 if offset is None else offset

    if count is None:
        # get all names after this offset
        count = get_num_names(proxy=proxy, hostport=hostport)
        if json_is_error(count):
            # error
            return count

        count -= offset

    page_size = 100
    all_names = []
    while len(all_names) < count:
        request_size = page_size
        if count - len(all_names) < request_size:
            request_size = count - len(all_names)

        page = get_all_names_page(offset + len(all_names), request_size, include_expired=include_expired, proxy=proxy, hostport=hostport)
        if json_is_error(page):
            # error
            return page

        if len(page) > request_size:
            # error
            error_str = 'server replied too much data'
            return {'error': error_str, 'http_status': 503}
        elif len(page) == 0:
            # end-of-table
            break

        all_names += page

    return all_names
743825
def _sub_hostname(self, line):
        '''
        
        '''
        try:
            for od,d in self.dn_db.items():
                #regex = re.compile(r'\w*\.%s' % d)
                regex = re.compile(r'(?![\W\-\:\ \.])[a-zA-Z0-9\-\_\.]*\.%s' % d)
                hostnames = [each for each in regex.findall(line)]
                if len(hostnames) > 0:
                    for hn in hostnames:
                        new_hn = self._hn2db(hn)
                        self.logger.debug("Obfuscating FQDN - %s > %s", hn, new_hn)
                        line = line.replace(hn, new_hn)
            if self.hostname:
                line = line.replace(self.hostname, self._hn2db(self.hostname))  #catch any non-fqdn instances of the system hostname

            return line
        except Exception as e: # pragma: no cover
            self.logger.exception(e)
            raise Exception('SubHostnameError: Unable to Substitute Hostname/Domainname')
74725
def valid_hostname(host):
    
    if len(host) > 255:
        return False

    if host[-1:] == '.':
        host = host[:-1]

    return all(_hostname_re.match(c) for c in host.split('.'))
531514
private String getHostHeaderForHost(String hostName) {
        List<ServerRedirect> servers = serverRedirectService.tableServers(requestInformation.get().client.getId());
        for (ServerRedirect server : servers) {
            if (server.getSrcUrl().compareTo(hostName) == 0) {
                String hostHeader = server.getHostHeader();
                if (hostHeader == null || hostHeader.length() == 0) {
                    return null;
                }
                return hostHeader;
            }
        }
        return null;
    }
517566
function hostnameof (req) {
  var host = req.headers.host

  if (!host) {
    return
  }

  var offset = host[0] === '['
    ? host.indexOf(']') + 1
    : 0
  var index = host.indexOf(':', offset)

  return index !== -1
    ? host.substring(0, index)
    : host
}
1283095
def filter_wildcard(names, pattern):
    
    return tuple(name for name in names
                 if fnmatch.fnmatch(name, pattern))