Python socket.getfqdn方法代码示例

本文整理汇总了Python中socket.getfqdn方法的典型用法代码示例。如果您正苦于以下问题:Python socket.getfqdn方法的具体用法?Python socket.getfqdn怎么用?Python socket.getfqdn使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块socket的用法示例。

在下文中一共展示了socket.getfqdn方法的21个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_host_is_local

# 需要导入模块: import socket [as 别名]
# 或者: from socket import getfqdn [as 别名]
def test_host_is_local():
    """test for neat.distributed.host_is_local"""
    tests = (
        # (hostname or ip, expected value)
        ("localhost", True),
        ("0.0.0.0", True),
        ("127.0.0.1", True),
        # ("::1", True), # depends on IP, etc setup on host to work right
        (socket.gethostname(), True),
        (socket.getfqdn(), True),
        ("github.com", False),
        ("google.de", False),
    )
    for hostname, islocal in tests:
        try:
            result = neat.host_is_local(hostname)
        except EnvironmentError:  # give more feedback
            print("test_host_is_local: Error with hostname {0!r} (expected {1!r})".format(hostname,
                                                                                          islocal))
            raise
        else:  # if do not want to do 'raise' above for some cases
            assert result == islocal, "Hostname/IP: {h}; Expected: {e}; Got: {r!r}".format(
                h=hostname, e=islocal, r=result) 
开发者ID:CodeReclaimers,项目名称:neat-python,代码行数:25,代码来源:test_distributed.py


示例2: host_is_local

# 需要导入模块: import socket [as 别名]
# 或者: from socket import getfqdn [as 别名]
def host_is_local(hostname, port=22): # no port specified, just use the ssh port
    """
    Returns True if the hostname points to the localhost, otherwise False.
    """
    hostname = socket.getfqdn(hostname)
    if hostname in ("localhost", "0.0.0.0", "127.0.0.1", "1.0.0.127.in-addr.arpa",
                    "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa"):
        return True
    localhost = socket.gethostname()
    if hostname == localhost:
        return True
    localaddrs = socket.getaddrinfo(localhost, port)
    targetaddrs = socket.getaddrinfo(hostname, port)
    for (ignored_family, ignored_socktype, ignored_proto, ignored_canonname,
         sockaddr) in localaddrs:
        for (ignored_rfamily, ignored_rsocktype, ignored_rproto,
             ignored_rcanonname, rsockaddr) in targetaddrs:
            if rsockaddr[0] == sockaddr[0]:
                return True
    return False 
开发者ID:CodeReclaimers,项目名称:neat-python,代码行数:22,代码来源:distributed.py


示例3: make_msgid

# 需要导入模块: import socket [as 别名]
# 或者: from socket import getfqdn [as 别名]
def make_msgid(idstring=None, domain=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:
    <20020201195627.33539.96671@nightshade.la.mastaler.com>
    Optional idstring if given is a string used to strengthen the
    uniqueness of the message id.  Optional domain if given provides the
    portion of the message id after the '@'.  It defaults to the locally
    defined hostname.
    """
    timeval = time.time()
    utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
    pid = os.getpid()
    randint = random.randrange(100000)
    if idstring is None:
        idstring = ''
    else:
        idstring = '.' + idstring
    if domain is None:
        domain = socket.getfqdn()
    msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, domain)
    return msgid 
开发者ID:Soft8Soft,项目名称:verge3d-blender-addon,代码行数:24,代码来源:utils.py


示例4: get_host_ip

# 需要导入模块: import socket [as 别名]
# 或者: from socket import getfqdn [as 别名]
def get_host_ip(hostIP=None):
    if hostIP is None or hostIP == 'auto':
        hostIP = 'ip'
    if hostIP == 'dns':
        hostIP = socket.getfqdn()
    elif hostIP == 'ip':
        from socket import gaierror
        try:
            hostIP = socket.gethostbyname(socket.getfqdn())
        except gaierror:
            logger.warn('gethostbyname(socket.getfqdn()) failed... trying on hostname()')
            hostIP = socket.gethostbyname(socket.gethostname())
        if hostIP.startswith("127."):
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            # doesn't have to be reachable
            s.connect(('10.255.255.255', 1))
            hostIP = s.getsockname()[0]
    return hostIP 
开发者ID:aws,项目名称:sagemaker-xgboost-container,代码行数:21,代码来源:tracker.py


示例5: test_set_header

# 需要导入模块: import socket [as 别名]
# 或者: from socket import getfqdn [as 别名]
def test_set_header(pkg):
    replog = ResultLog()
    d = replog.dict
    assert replog.dict == d
    assert replog.dict["reportversion"] == "1"
    assert replog.dict["toxversion"] == tox.__version__
    assert replog.dict["platform"] == sys.platform
    assert replog.dict["host"] == socket.getfqdn()
    expected = {"basename": "hello-1.0.tar.gz", "sha256": pkg.computehash("sha256")}
    env_log = replog.get_envlog("a")
    env_log.set_header(installpkg=pkg)
    assert env_log.dict["installpkg"] == expected
    data = replog.dumps_json()
    replog2 = ResultLog.from_json(data)
    assert replog2.dict == replog.dict 
开发者ID:tox-dev,项目名称:tox,代码行数:18,代码来源:test_result.py


示例6: reserve_sock_addr

# 需要导入模块: import socket [as 别名]
# 或者: from socket import getfqdn [as 别名]
def reserve_sock_addr() -> Iterator[Tuple[str, int]]:
    """Reserve an available TCP port to listen on.
    The reservation is done by binding a TCP socket to port 0 with
    ``SO_REUSEPORT`` flag set (requires Linux >=3.9). The socket is
    then kept open until the generator is closed.
    To reduce probability of 'hijacking' port, socket should stay open
    and should be closed _just before_ starting of ``tf.train.Server``
    """
    so_reuseport = get_so_reuseport()
    if so_reuseport is None:
        raise RuntimeError(
            "SO_REUSEPORT is not supported by the operating system") from None
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.setsockopt(socket.SOL_SOCKET, so_reuseport, 1)
        sock.bind(("", 0))
        _ipaddr, port = sock.getsockname()
        yield (socket.getfqdn(), port) 
开发者ID:criteo,项目名称:tf-yarn,代码行数:22,代码来源:_internal.py


示例7: report_failure

# 需要导入模块: import socket [as 别名]
# 或者: from socket import getfqdn [as 别名]
def report_failure(self, server_uuid, errno):
        """Report failure to Fabric
        This method sets the status of a MySQL server identified by
        server_uuid.
        """
        if not self._report_errors:
            return
        errno = int(errno)
        current_host = socket.getfqdn()
        if errno in REPORT_ERRORS or errno in REPORT_ERRORS_EXTRA:
            _LOGGER.debug("Reporting error %d of server %s", errno,
                          server_uuid)
            inst = self.get_instance()
            try:
                data = inst.execute('threat', 'report_failure',
                                    server_uuid, current_host, errno)
                FabricResponse(data)
            except (Fault, socket.error) as exc:
                _LOGGER.debug("Failed reporting server to Fabric (%s)",
                              str(exc))
                # Not requiring further action 
开发者ID:LuciferJack,项目名称:python-mysql-pool,代码行数:26,代码来源:connection.py


示例8: getfqdn

# 需要导入模块: import socket [as 别名]
# 或者: from socket import getfqdn [as 别名]
def getfqdn(address, timeout=0.5):
    # note: cannot use timeout lib because signal must be run from the
    #       main thread
    result = [address]
    def helper():
        result[0] = socket.getfqdn(address)
    t = threading.Thread(target=helper)
    t.daemon = True
    t.start()
    t.join(timeout)
    return result[0] 
开发者ID:aerospike,项目名称:aerospike-admin,代码行数:19,代码来源:node.py


示例9: make_msgid

# 需要导入模块: import socket [as 别名]
# 或者: from socket import getfqdn [as 别名]
def make_msgid(idstring=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:
    <20020201195627.33539.96671@nightshade.la.mastaler.com>
    Optional idstring if given is a string used to strengthen the
    uniqueness of the message id.
    """
    timeval = time.time()
    utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
    pid = os.getpid()
    randint = random.randrange(100000)
    if idstring is None:
        idstring = ''
    else:
        idstring = '.' + idstring
    idhost = socket.getfqdn()
    msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, idhost)
    return msgid
# These functions are in the standalone mimelib version only because they've
# subsequently been fixed in the latest Python versions.  We use this to worm
# around broken older Pythons. 
开发者ID:glmcdona,项目名称:meddle,代码行数:27,代码来源:utils.py


示例10: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import getfqdn [as 别名]
def __init__(self, server, conn, addr):
        asynchat.async_chat.__init__(self, conn)
        self.__server = server
        self.__conn = conn
        self.__addr = addr
        self.__line = []
        self.__state = self.COMMAND
        self.__greeting = 0
        self.__mailfrom = None
        self.__rcpttos = []
        self.__data = ''
        self.__fqdn = socket.getfqdn()
        try:
            self.__peer = conn.getpeername()
        except socket.error, err:
            # a race condition  may occur if the other end is closing
            # before we can get the peername
            self.close()
            if err[0] != errno.ENOTCONN:
                raise
            return 
开发者ID:glmcdona,项目名称:meddle,代码行数:23,代码来源:smtpd.py


示例11: make_msgid

# 需要导入模块: import socket [as 别名]
# 或者: from socket import getfqdn [as 别名]
def make_msgid(idstring=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:
    <142480216486.20800.16526388040877946887@nightshade.la.mastaler.com>
    Optional idstring if given is a string used to strengthen the
    uniqueness of the message id.
    """
    timeval = int(time.time()*100)
    pid = os.getpid()
    randint = random.getrandbits(64)
    if idstring is None:
        idstring = ''
    else:
        idstring = '.' + idstring
    idhost = socket.getfqdn()
    msgid = '<%d.%d.%d%s@%s>' % (timeval, pid, randint, idstring, idhost)
    return msgid
# These functions are in the standalone mimelib version only because they've
# subsequently been fixed in the latest Python versions.  We use this to worm
# around broken older Pythons. 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:26,代码来源:utils.py


示例12: testHostnameRes

# 需要导入模块: import socket [as 别名]
# 或者: from socket import getfqdn [as 别名]
def testHostnameRes(self):
        # Testing hostname resolution mechanisms
        hostname = socket.gethostname()
        try:
            ip = socket.gethostbyname(hostname)
        except socket.error:
            # Probably name lookup wasn't set up right; skip this test
            self.skipTest('name lookup failure')
        self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
        try:
            hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
        except socket.error:
            # Probably a similar problem as above; skip this test
            self.skipTest('address lookup failure')
        all_host_names = [hostname, hname] + aliases
        fqhn = socket.getfqdn(ip)
        if not fqhn in all_host_names:
            self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:20,代码来源:test_socket.py


示例13: testHostnameRes

# 需要导入模块: import socket [as 别名]
# 或者: from socket import getfqdn [as 别名]
def testHostnameRes(self):
        # Testing hostname resolution mechanisms
        hostname = socket.gethostname()
        try:
            ip = socket.gethostbyname(hostname)
        except socket.error:
            # Probably name lookup wasn't set up right; skip this test
            return
        self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
        try:
            hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
        except socket.error:
            # Probably a similar problem as above; skip this test
            return
        all_host_names = [hostname, hname] + aliases
        fqhn = socket.getfqdn(ip)
        if not fqhn in all_host_names:
            self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) 
开发者ID:dxwu,项目名称:BinderFilter,代码行数:20,代码来源:test_socket.py


示例14: ptr_lookup

# 需要导入模块: import socket [as 别名]
# 或者: from socket import getfqdn [as 别名]
def ptr_lookup(cls, network):
        ip = str(ipaddress.ip_interface(network).ip)
        try:
            primary_hostname, alias_hostnames, other_ips = socket.gethostbyaddr(ip)
        except socket.herror as e:
            logger.debug('DNS Reverse Lookup Error {}'.format(e))
            return Html.div('DNS: n/a')
        content = Html.div(
            'DNS: {}'.format(
                socket.getfqdn(primary_hostname)
            )
        )
        if alias_hostnames:
            content += Html.div('DNS Aliases:')
        for hostname in alias_hostnames:
            fqdn_hostname = socket.getfqdn(hostname)
            logger.debug('Alias {} FQDN {}'.format(hostname, fqdn_hostname))
            content += Html.div(fqdn_hostname)
        return content 
开发者ID:heyglen,项目名称:network_tech,代码行数:23,代码来源:network.py


示例15: set_from_reporting_config_json

# 需要导入模块: import socket [as 别名]
# 或者: from socket import getfqdn [as 别名]
def set_from_reporting_config_json():
    # global hostname, hostnameShort
    report_file_name = "reporting_config.json"
    # reading file form reporting_config.json
    with open(os.path.join(home_path, report_file_name), 'r') as f:
        config = json.load(f)
    reporting_interval_string = config['reporting_interval']
    # is_second_reporting = False
    if reporting_interval_string[-1:] == 's':
        # is_second_reporting = True
        reporting_interval_l = float(config['reporting_interval'][:-1])
        reporting_interval_l = float(reporting_interval_l / 60)
    else:
        reporting_interval_l = int(config['reporting_interval'])
    # keep_file_days = int(config['keep_file_days'])
    prev_endtime_l = config['prev_endtime']
    # deltaFields_l = config['delta_fields']
    hostname_l = socket.getfqdn()
    hostname_short_l = socket.gethostname().partition(".")[0]
    csvpath_l = "/var/lib/collectd/csv/" + hostname_short_l
    if not os.path.exists(csvpath_l):
        csvpath_l = "/var/lib/collectd/csv/" + hostname_l
    if not os.path.exists(csvpath_l):
        directory_list = os.listdir("/var/lib/collectd/csv")
        if len(directory_list) > 0:
            csvpath_l = "/var/lib/collectd/csv/" + directory_list[0]
    date_l = time.strftime("%Y-%m-%d")
    return reporting_interval_l, hostname_l, hostname_short_l, prev_endtime_l, csvpath_l, date_l
# deletes old csv files from a directory 
开发者ID:insightfinder,项目名称:InsightAgent,代码行数:39,代码来源:collectdReportMetrics.py


示例16: _get_node_rp_uuid

# 需要导入模块: import socket [as 别名]
# 或者: from socket import getfqdn [as 别名]
def _get_node_rp_uuid(self, context, node):
        if self.rp_uuid:
            return self.rp_uuid
        if CONF.compute.host_shared_with_nova:
            try:
                self.rp_uuid = self.reportclient.get_provider_by_name(
                    context, node.hostname)['uuid']
            except exception.ResourceProviderNotFound:
                # NOTE(hongbin): cannot find the resource provider created
                # by nova. Probably, the configured hostname in Zun doesn't
                # match the hypervisor_hostname in nova.
                # We give a few more tries with possible hostname.
                possible_rp_names = [socket.gethostname(), socket.getfqdn()]
                for name in possible_rp_names:
                    try:
                        self.rp_uuid = self.reportclient.get_provider_by_name(
                            context, name)['uuid']
                        break
                    except exception.ResourceProviderNotFound:
                        pass
                if not self.rp_uuid:
                    raise exception.ComputeHostNotFound(host=node.hostname)
        else:
            self.rp_uuid = node.uuid
        return self.rp_uuid 
开发者ID:openstack,项目名称:zun,代码行数:30,代码来源:compute_node_tracker.py


示例17: get_window_name

# 需要导入模块: import socket [as 别名]
# 或者: from socket import getfqdn [as 别名]
def get_window_name():
    """获取window系统名"""
    return socket.getfqdn(socket.gethostname()) 
开发者ID:jtyoui,项目名称:Jtyoui,代码行数:5,代码来源:gateway.py


示例18: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import getfqdn [as 别名]
def __init__(self):
        command_log = []
        self.command_log = CommandLog(None, command_log)
        self.dict = {
            "reportversion": "1",
            "toxversion": __version__,
            "platform": sys.platform,
            "host": socket.getfqdn(),
            "commands": command_log,
        } 
开发者ID:tox-dev,项目名称:tox,代码行数:12,代码来源:result.py


示例19: test_pre_set_header

# 需要导入模块: import socket [as 别名]
# 或者: from socket import getfqdn [as 别名]
def test_pre_set_header():
    replog = ResultLog()
    d = replog.dict
    assert replog.dict == d
    assert replog.dict["reportversion"] == "1"
    assert replog.dict["toxversion"] == tox.__version__
    assert replog.dict["platform"] == sys.platform
    assert replog.dict["host"] == socket.getfqdn()
    data = replog.dumps_json()
    replog2 = ResultLog.from_json(data)
    assert replog2.dict == replog.dict 
开发者ID:tox-dev,项目名称:tox,代码行数:13,代码来源:test_result.py


示例20: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import getfqdn [as 别名]
def __init__(self, **kw):
        super(ComputeFQDNEnvironmentMixin, self).__init__(
            fqdn=socket.getfqdn(), **kw
        ) 
开发者ID:Pagure,项目名称:pagure,代码行数:6,代码来源:git_multimail_upstream.py


示例21: get_localhost_details

# 需要导入模块: import socket [as 别名]
# 或者: from socket import getfqdn [as 别名]
def get_localhost_details(interfaces_eth, interfaces_wlan):
    hostdata = "None"
    hostname = "None"
    windows_ip = "None"
    eth_ip = "None"
    wlan_ip = "None"
    host_fqdn = "None"
    eth_mac = "None"
    wlan_mac = "None"
    windows_mac = "None"
    hostname = socket.gethostbyname(socket.gethostname())
    if hostname.startswith("127.") and os.name != "nt":
        hostdata = socket.gethostbyaddr(socket.gethostname())
        hostname = str(hostdata[1]).strip('[]')
        host_fqdn = socket.getfqdn()
        for interface in interfaces_eth:
            try:
                eth_ip = get_ip(interface)
                if not "None" in eth_ip:
                    eth_mac = get_mac_address(interface)
                break
            except IOError:
                pass
        for interface in interfaces_wlan:
            try:
                wlan_ip = get_ip(interface)
                if not "None" in wlan_ip:
                    wlan_mac = get_mac_address(interface)
                break
            except IOError:
                pass
    else:
        windows_ip = socket.gethostbyname(socket.gethostname())
        windows_mac = uuid.getnode()
        windows_mac = ':'.join(("%012X" % windows_mac)[i:i+2] for i in range(0, 12, 2))
        hostdata = socket.gethostbyaddr(socket.gethostname())
        hostname = str(socket.gethostname())
        host_fqdn = socket.getfqdn()
    return hostdata, hostname, windows_ip, eth_ip, wlan_ip, host_fqdn, eth_mac, wlan_mac, windows_mac 
开发者ID:funkandwagnalls,项目名称:pythonpentest,代码行数:41,代码来源:hostdetails.py



注:本文中的socket.getfqdn方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。