本文整理汇总了Python中socket.getfqdn方法的典型用法代码示例。如果您正苦于以下问题:Python socket.getfqdn方法的具体用法?Python socket.getfqdn怎么用?Python socket.getfqdn使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类socket
的用法示例。
在下文中一共展示了socket.getfqdn方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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
示例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
示例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
示例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
示例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)
示例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
示例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]
示例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.
示例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
示例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.
示例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)))
示例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)))
示例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
示例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