Python socket.getfqdn() Examples

The following are code examples for showing how to use socket.getfqdn(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: utils.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def make_msgid(idstring=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:

    <[email protected]>

    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%[email protected]%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. 
Example 2
Project: pyblish-win   Author: pyblish   File: smtpd.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
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 
Example 3
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
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))) 
Example 4
Project: CVE-2018-7750   Author: jm33-m0   File: sample_ssh_server.py    GNU General Public License v3.0 6 votes vote down vote up
def listener():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('', 2222))

    sock.listen(100)
    client, addr = sock.accept()

    t = paramiko.Transport(client)
    t.set_gss_host(socket.getfqdn(""))
    t.load_server_moduli()
    t.add_server_key(host_key)
    server = Server()
    t.start_server(server=server)

    # Wait 30 seconds for a command
    server.event.wait(30)
    t.close() 
Example 5
Project: Repobot   Author: Desgard   File: utils.py    MIT License 6 votes vote down vote up
def make_msgid(idstring=None, domain=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:

    <[email protected]>

    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%[email protected]%s>' % (utcdate, pid, randint, idstring, domain)
    return msgid 
Example 6
Project: neat-python   Author: CodeReclaimers   File: test_distributed.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example 7
Project: neat-python   Author: CodeReclaimers   File: distributed.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example 8
Project: sagemaker-xgboost-container   Author: aws   File: tracker.py    Apache License 2.0 6 votes vote down vote up
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 
Example 9
Project: Flask_Blog   Author: sugarguo   File: utils.py    GNU General Public License v3.0 6 votes vote down vote up
def make_msgid(idstring=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:

    <[email protected]>

    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%[email protected]%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. 
Example 10
Project: NiujiaoDebugger   Author: MrSrc   File: utils.py    GNU General Public License v3.0 6 votes vote down vote up
def make_msgid(idstring=None, domain=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:

    <[email protected]om>

    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 = int(time.time()*100)
    pid = os.getpid()
    randint = random.getrandbits(64)
    if idstring is None:
        idstring = ''
    else:
        idstring = '.' + idstring
    if domain is None:
        domain = socket.getfqdn()
    msgid = '<%d.%d.%d%[email protected]%s>' % (timeval, pid, randint, idstring, domain)
    return msgid 
Example 11
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 6 votes vote down vote up
def testHostnameRes(self):
        # Testing hostname resolution mechanisms
        hostname = socket.gethostname()
        try:
            ip = socket.gethostbyname(hostname)
        except OSError:
            # 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 OSError:
            # Probably a similar problem as above; skip this test
            self.skipTest('name 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))) 
Example 12
Project: NiujiaoDebugger   Author: MrSrc   File: test_smtplib.py    GNU General Public License v3.0 6 votes vote down vote up
def setUp(self):
        self.real_getfqdn = socket.getfqdn
        socket.getfqdn = mock_socket.getfqdn
        self.serv_evt = threading.Event()
        self.client_evt = threading.Event()
        # Pick a random unused port by passing 0 for the port number
        self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1), decode_data=True)
        # Keep a note of what port was assigned
        self.port = self.serv.socket.getsockname()[1]
        serv_args = (self.serv, self.serv_evt, self.client_evt)
        self.thread = threading.Thread(target=debugging_server, args=serv_args)
        self.thread.start()

        # wait until server thread has assigned a port number
        self.serv_evt.wait()
        self.serv_evt.clear() 
Example 13
Project: NiujiaoDebugger   Author: MrSrc   File: test_smtplib.py    GNU General Public License v3.0 6 votes vote down vote up
def setUp(self):
        self.real_getfqdn = socket.getfqdn
        socket.getfqdn = mock_socket.getfqdn
        self.serv_evt = threading.Event()
        self.client_evt = threading.Event()
        # Pick a random unused port by passing 0 for the port number
        self.serv = SimSMTPUTF8Server((HOST, 0), ('nowhere', -1),
                                      decode_data=False,
                                      enable_SMTPUTF8=True)
        # Keep a note of what port was assigned
        self.port = self.serv.socket.getsockname()[1]
        serv_args = (self.serv, self.serv_evt, self.client_evt)
        self.thread = threading.Thread(target=debugging_server, args=serv_args)
        self.thread.start()

        # wait until server thread has assigned a port number
        self.serv_evt.wait()
        self.serv_evt.clear() 
Example 14
Project: tox   Author: tox-dev   File: test_result.py    MIT License 6 votes vote down vote up
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 
Example 15
Project: tf-yarn   Author: criteo   File: _internal.py    Apache License 2.0 6 votes vote down vote up
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) 
Example 16
Project: rucio   Author: rucio   File: uploadclient.py    Apache License 2.0 6 votes vote down vote up
def __init__(self, _client=None, logger=None, tracing=True):
        """
        Initialises the basic settings for an UploadClient object

        :param _client:     - Optional: rucio.client.client.Client object. If None, a new object will be created.
        :param logger:      - logging.Logger object to use for uploads. If None nothing will be logged.
        """
        if not logger:
            logger = logging.getLogger('%s.null' % __name__)
            logger.disabled = True

        self.logger = logger
        self.client = _client if _client else Client()
        self.tracing = tracing
        if not self.tracing:
            logger.debug('Tracing is turned off.')
        self.default_file_scope = 'user.' + self.client.account
        self.rses = {}

        self.trace = {}
        self.trace['hostname'] = socket.getfqdn()
        self.trace['account'] = self.client.account
        self.trace['eventType'] = 'upload'
        self.trace['eventVersion'] = version.RUCIO_VERSION[0] 
Example 17
Project: munch-core   Author: crunchmail   File: models.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def save(self, *args, **kwargs):
        created = not self.pk

        self.update_mail_status()

        if self.status_code:
            status_code = rfc3463_regex.match(self.status_code)
            if status_code:
                self.status_code = status_code.group(0)

        if not self.pk:
            if not self.creation_date:
                self.creation_date = timezone.now()
            if not self.source_hostname:
                self.source_hostname = socket.getfqdn()
        super().save(*args, **kwargs)

        if created and self.status in [self.DROPPED, self.BOUNCED]:
            self.should_optout(create=True) 
Example 18
Project: qis   Author: quru   File: util.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def this_is_computer(net_name):
    """
    Returns whether a computer network name or IP address appears to be this
    (the current) computer. True is returned for 'localhost', the loopback
    network address, or any other host name or IP address that matches the
    current network configuration.
    """
    try_names = [
        'localhost',
        socket.getfqdn(),
        socket.gethostname()
    ]
    server_names = []
    server_addrs = []
    try:
        for name in try_names:
            (hostname, aliaslist, ipaddrlist) = socket.gethostbyname_ex(name)
            server_names.append(hostname)
            server_names.extend(aliaslist)
            server_addrs.extend(ipaddrlist)
        return (net_name in server_names) or (net_name in server_addrs)
    except socket.gaierror:
        # No DNS service is available
        return net_name in ['localhost', '127.0.0.1', '::1'] 
Example 19
Project: oa_qian   Author: sunqb   File: barrier.py    Apache License 2.0 6 votes vote down vote up
def __init__(self, client, path, num_clients, identifier=None):
        """Create a Double Barrier

        :param client: A :class:`~kazoo.client.KazooClient` instance.
        :param path: The barrier path to use.
        :param num_clients: How many clients must enter the barrier to
                            proceed.
        :type num_clients: int
        :param identifier: An identifier to use for this member of the
                           barrier when participating. Defaults to the
                           hostname + process id.

        """
        self.client = client
        self.path = path
        self.num_clients = num_clients
        self._identifier = identifier or '%s-%s' % (
            socket.getfqdn(), os.getpid())
        self.participating = False
        self.assured_path = False
        self.node_name = uuid.uuid4().hex
        self.create_path = self.path + "/" + self.node_name 
Example 20
Project: ironpython2   Author: IronLanguages   File: utils.py    Apache License 2.0 6 votes vote down vote up
def make_msgid(idstring=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:

    <[email protected]om>

    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%[email protected]%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. 
Example 21
Project: ironpython2   Author: IronLanguages   File: smtpd.py    Apache License 2.0 6 votes vote down vote up
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 
Example 22
Project: ironpython2   Author: IronLanguages   File: test_socket.py    Apache License 2.0 6 votes vote down vote up
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))) 
Example 23
Project: fs_image   Author: facebookincubator   File: subvolume_on_disk.py    MIT License 5 votes vote down vote up
def from_subvolume_path(
        cls,
        subvol_path: str,
        subvolumes_dir: str,
    ):
        subvol_rel_path = os.path.relpath(subvol_path, subvolumes_dir)
        pieces = subvol_rel_path.split('/')
        if pieces[:1] == [''] or '..' in pieces:
            raise RuntimeError(
                f'{subvol_path} must be located inside the subvolumes '
                f'directory {subvolumes_dir}'
            )
        # This function deliberately does no validation on the fields it
        # populates -- that is done only in `from_serializable_dict`.  We
        # will not commit a buggy structure to disk since
        # `to_serializable_dict` checks the idepmpotency of our
        # serialization-deserialization.
        volume_props = _btrfs_get_volume_props(subvol_path)
        self = cls(**{
            _BTRFS_UUID: volume_props['UUID'],
            _BTRFS_PARENT_UUID: volume_props['Parent UUID'],
            _HOSTNAME: socket.getfqdn(),
            _SUBVOLUMES_BASE_DIR: subvolumes_dir,
            _SUBVOLUME_REL_PATH: subvol_rel_path,
        })
        return self 
Example 24
Project: pyblish-win   Author: pyblish   File: smtplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, host='', port=0, local_hostname=None,
                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
        """Initialize a new instance.

        If specified, `host' is the name of the remote host to which to
        connect.  If specified, `port' specifies the port to which to connect.
        By default, smtplib.SMTP_PORT is used.  If a host is specified the
        connect method is called, and if it returns anything other than a
        success code an SMTPConnectError is raised.  If specified,
        `local_hostname` is used as the FQDN of the local host for the
        HELO/EHLO command.  Otherwise, the local hostname is found using
        socket.getfqdn().

        """
        self.timeout = timeout
        self.esmtp_features = {}
        if host:
            (code, msg) = self.connect(host, port)
            if code != 220:
                raise SMTPConnectError(code, msg)
        if local_hostname is not None:
            self.local_hostname = local_hostname
        else:
            # RFC 2821 says we should use the fqdn in the EHLO/HELO verb, and
            # if that can't be calculated, that we should use a domain literal
            # instead (essentially an encoded IP address like [A.B.C.D]).
            fqdn = socket.getfqdn()
            if '.' in fqdn:
                self.local_hostname = fqdn
            else:
                # We can't find an fqdn hostname, so use a domain literal
                addr = '127.0.0.1'
                try:
                    addr = socket.gethostbyname(socket.gethostname())
                except socket.gaierror:
                    pass
                self.local_hostname = '[%s]' % addr 
Example 25
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor.py    MIT License 5 votes vote down vote up
def __init__(self, module, **params):
        self.__version__ = "1.0-python"
        self.module = module
        self.module.debug("Instantiating LogicMonitor object")

        self.check_mode = False
        self.company = params["company"]
        self.user = params["user"]
        self.password = params["password"]
        self.fqdn = socket.getfqdn()
        self.lm_url = "logicmonitor.com/santaba"
        self.__version__ = self.__version__ + "-ansible-module" 
Example 26
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor_facts.py    MIT License 5 votes vote down vote up
def __init__(self, module, **params):
        self.__version__ = "1.0-python"
        self.module = module
        self.module.debug("Instantiating LogicMonitor object")

        self.check_mode = False
        self.company = params["company"]
        self.user = params["user"]
        self.password = params["password"]
        self.fqdn = socket.getfqdn()
        self.lm_url = "logicmonitor.com/santaba"
        self.__version__ = self.__version__ + "-ansible-module" 
Example 27
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: hostname.py    MIT License 5 votes vote down vote up
def main():
    module = AnsibleModule(
        argument_spec=dict(
            name=dict(required=True)
        ),
        supports_check_mode=True,
    )

    hostname = Hostname(module)
    name = module.params['name']

    current_hostname = hostname.get_current_hostname()
    permanent_hostname = hostname.get_permanent_hostname()

    changed = hostname.update_current_and_permanent_hostname()

    if name != current_hostname:
        name_before = current_hostname
    elif name != permanent_hostname:
        name_before = permanent_hostname

    kw = dict(changed=changed, name=name,
              ansible_facts=dict(ansible_hostname=name.split('.')[0],
                                 ansible_nodename=name,
                                 ansible_fqdn=socket.getfqdn(),
                                 ansible_domain='.'.join(socket.getfqdn().split('.')[1:])))

    if changed:
        kw['diff'] = {'after': 'hostname = ' + name + '\n',
                      'before': 'hostname = ' + name_before + '\n'}

    module.exit_json(**kw) 
Example 28
Project: AshsSDK   Author: thehappydinoa   File: client.py    MIT License 5 votes vote down vote up
def connect_srv(self, domain=None, keepalive=60, bind_address=""):
        """Connect to a remote broker.

        domain is the DNS domain to search for SRV records; if None,
        try to determine local domain name.
        keepalive and bind_address are as for connect()
        """

        if HAVE_DNS is False:
            raise ValueError('No DNS resolver library found.')

        if domain is None:
            domain = socket.getfqdn()
            domain = domain[domain.find('.') + 1:]

        try:
            rr = '_mqtt._tcp.%s' % domain
            if self._ssl is not None:
                # IANA specifies secure-mqtt (not mqtts) for port 8883
                rr = '_secure-mqtt._tcp.%s' % domain
            answers = []
            for answer in dns.resolver.query(rr, dns.rdatatype.SRV):
                addr = answer.target.to_text()[:-1]
                answers.append((addr, answer.port, answer.priority, answer.weight))
        except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers):
            raise ValueError("No answer/NXDOMAIN for SRV in %s" % (domain))

        # FIXME: doesn't account for weight
        for answer in answers:
            host, port, prio, weight = answer

            try:
                return self.connect(host, port, keepalive, bind_address)
            except:
                pass

        raise ValueError("No SRV hosts responded") 
Example 29
Project: InsightAgent   Author: insightfinder   File: collectdReportMetrics.py    Apache License 2.0 5 votes vote down vote up
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 
Example 30
Project: deb-python-cassandra-driver   Author: openstack   File: policies.py    Apache License 2.0 5 votes vote down vote up
def translate(self, addr):
        """
        Reverse DNS the public broadcast_address, then lookup that hostname to get the AWS-resolved IP, which
        will point to the private IP address within the same datacenter.
        """
        # get family of this address so we translate to the same
        family = socket.getaddrinfo(addr, 0, socket.AF_UNSPEC, socket.SOCK_STREAM)[0][0]
        host = socket.getfqdn(addr)
        for a in socket.getaddrinfo(host, 0, family, socket.SOCK_STREAM):
            try:
                return a[4][0]
            except Exception:
                pass
        return addr 
Example 31
Project: osg-configure   Author: opensciencegrid   File: utilities.py    Apache License 2.0 5 votes vote down vote up
def get_hostname():
    """Returns the hostname of the current system"""
    try:
        return socket.getfqdn()
    except socket.error:
        return None 
Example 32
Project: Jtyoui   Author: jtyoui   File: gateway.py    MIT License 5 votes vote down vote up
def get_window_name():
    """获取window系统名"""
    return socket.getfqdn(socket.gethostname()) 
Example 33
Project: zigmo   Author: leohowell   File: wsgi_server.py    MIT License 5 votes vote down vote up
def __init__(self, server_address):
        self.ssocket = self.setup_server_socket(server_address)
        host, self.server_port = self.ssocket.getsockname()[:2]
        self.server_name = socket.getfqdn(host)

        self.ioloop = IOLoop.instance()
        self.conn_pool = {} 
Example 34
Project: NiujiaoDebugger   Author: MrSrc   File: smtpd.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, server, conn, addr, data_size_limit=DATA_SIZE_DEFAULT,
                 map=None, enable_SMTPUTF8=False, decode_data=False):
        asynchat.async_chat.__init__(self, conn, map=map)
        self.smtp_server = server
        self.conn = conn
        self.addr = addr
        self.data_size_limit = data_size_limit
        self.enable_SMTPUTF8 = enable_SMTPUTF8
        self._decode_data = decode_data
        if enable_SMTPUTF8 and decode_data:
            raise ValueError("decode_data and enable_SMTPUTF8 cannot"
                             " be set to True at the same time")
        if decode_data:
            self._emptystring = ''
            self._linesep = '\r\n'
            self._dotsep = '.'
            self._newline = NEWLINE
        else:
            self._emptystring = b''
            self._linesep = b'\r\n'
            self._dotsep = ord(b'.')
            self._newline = b'\n'
        self._set_rset_state()
        self.seen_greeting = ''
        self.extended_smtp = False
        self.command_size_limits.clear()
        self.fqdn = socket.getfqdn()
        try:
            self.peer = conn.getpeername()
        except OSError as err:
            # a race condition  may occur if the other end is closing
            # before we can get the peername
            self.close()
            if err.args[0] != errno.ENOTCONN:
                raise
            return
        print('Peer:', repr(self.peer), file=DEBUGSTREAM)
        self.push('220 %s %s' % (self.fqdn, __version__)) 
Example 35
Project: NiujiaoDebugger   Author: MrSrc   File: test_email.py    GNU General Public License v3.0 5 votes vote down vote up
def test_make_msgid_default_domain(self):
        self.assertTrue(
            email.utils.make_msgid().endswith(
                '@' + getfqdn() + '>')) 
Example 36
Project: NiujiaoDebugger   Author: MrSrc   File: test_smtplib.py    GNU General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        socket.getfqdn = self.real_getfqdn
        # indicate that the client is finished
        self.client_evt.set()
        # wait for the server thread to terminate
        self.serv_evt.wait()
        self.thread.join()
        # restore sys.stdout
        sys.stdout = self.old_stdout
        # restore DEBUGSTREAM
        smtpd.DEBUGSTREAM.close()
        smtpd.DEBUGSTREAM = self.old_DEBUGSTREAM 
Example 37
Project: NiujiaoDebugger   Author: MrSrc   File: test_smtplib.py    GNU General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        socket.getfqdn = self.real_getfqdn
        # indicate that the client is finished
        self.client_evt.set()
        # wait for the server thread to terminate
        self.serv_evt.wait()
        self.thread.join() 
Example 38
Project: NiujiaoDebugger   Author: MrSrc   File: test_smtplib.py    GNU General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        socket.getfqdn = self.real_getfqdn
        # indicate that the client is finished
        self.client_evt.set()
        # wait for the server thread to terminate
        self.serv_evt.wait()
        self.thread.join() 
Example 39
Project: NiujiaoDebugger   Author: MrSrc   File: test_smtplib.py    GNU General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        socket.getfqdn = self.real_getfqdn
        # indicate that the client is finished
        self.client_evt.set()
        # wait for the server thread to terminate
        self.serv_evt.wait()
        self.thread.join() 
Example 40
Project: smaslennikov.github.io   Author: smaslennikov   File: urlserver.py    MIT License 5 votes vote down vote up
def urlserver_get_base_url():
    """
    Return url with port number if != default port for the protocol,
    including prefix path.
    """
    global urlserver_settings

    scheme = urlserver_settings['http_scheme_display']
    hostname = (urlserver_settings['http_hostname_display'] or
                urlserver_settings['http_hostname'] or socket.getfqdn())

    # If the built-in HTTP server isn't running, default to port from settings
    port = urlserver_settings['http_port']
    if len(urlserver_settings['http_port_display']) > 0:
        port = urlserver_settings['http_port_display']
    elif urlserver['socket']:
        port = urlserver['socket'].getsockname()[1]

    # Don't add :port if the port matches the default port for the protocol
    prefixed_port = ':%s' % port

    if scheme == "http" and prefixed_port == ':80':
        prefixed_port = ''
    elif scheme == "https" and prefixed_port == ':443':
        prefixed_port = ''

    prefix = ''
    if urlserver_settings['http_url_prefix']:
        prefix = '%s/' % urlserver_settings['http_url_prefix']

    return '%s://%s%s/%s' % (scheme, hostname, prefixed_port, prefix) 
Example 41
Project: smaslennikov.github.io   Author: smaslennikov   File: urlserver.py    MIT License 5 votes vote down vote up
def urlserver_server_start():
    """Start mini HTTP server."""
    global urlserver, urlserver_settings
    if urlserver['socket']:
        weechat.prnt('', 'URL server already running')
        return
    port = 0
    try:
        port = int(urlserver_settings['http_port'])
    except:
        port = 0
    urlserver['socket'] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    urlserver['socket'].setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        urlserver['socket'].bind((urlserver_settings['http_hostname'] or
                                  socket.getfqdn(), port))
    except Exception as e:
        weechat.prnt('', '%sBind error: %s' % (weechat.prefix('error'), e))
        urlserver['socket'] = None
        urlserver_server_status()
        return
    urlserver['socket'].listen(5)
    urlserver['hook_fd'] = weechat.hook_fd(urlserver['socket'].fileno(),
                                           1, 0, 0,
                                           'urlserver_server_fd_cb', '')
    urlserver_server_status() 
Example 42
Project: smaslennikov.github.io   Author: smaslennikov   File: urlserver.py    MIT License 5 votes vote down vote up
def urlserver_get_base_url():
    """
    Return url with port number if != default port for the protocol,
    including prefix path.
    """
    global urlserver_settings

    scheme = urlserver_settings['http_scheme_display']
    hostname = (urlserver_settings['http_hostname_display'] or
                urlserver_settings['http_hostname'] or socket.getfqdn())

    # If the built-in HTTP server isn't running, default to port from settings
    port = urlserver_settings['http_port']
    if len(urlserver_settings['http_port_display']) > 0:
        port = urlserver_settings['http_port_display']
    elif urlserver['socket']:
        port = urlserver['socket'].getsockname()[1]

    # Don't add :port if the port matches the default port for the protocol
    prefixed_port = ':%s' % port

    if scheme == "http" and prefixed_port == ':80':
        prefixed_port = ''
    elif scheme == "https" and prefixed_port == ':443':
        prefixed_port = ''

    prefix = ''
    if urlserver_settings['http_url_prefix']:
        prefix = '%s/' % urlserver_settings['http_url_prefix']

    return '%s://%s%s/%s' % (scheme, hostname, prefixed_port, prefix) 
Example 43
Project: smaslennikov.github.io   Author: smaslennikov   File: urlserver.py    MIT License 5 votes vote down vote up
def urlserver_server_start():
    """Start mini HTTP server."""
    global urlserver, urlserver_settings
    if urlserver['socket']:
        weechat.prnt('', 'URL server already running')
        return
    port = 0
    try:
        port = int(urlserver_settings['http_port'])
    except:
        port = 0
    urlserver['socket'] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    urlserver['socket'].setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        urlserver['socket'].bind((urlserver_settings['http_hostname'] or
                                  socket.getfqdn(), port))
    except Exception as e:
        weechat.prnt('', '%sBind error: %s' % (weechat.prefix('error'), e))
        urlserver['socket'] = None
        urlserver_server_status()
        return
    urlserver['socket'].listen(5)
    urlserver['hook_fd'] = weechat.hook_fd(urlserver['socket'].fileno(),
                                           1, 0, 0,
                                           'urlserver_server_fd_cb', '')
    urlserver_server_status() 
Example 44
Project: tox   Author: tox-dev   File: result.py    MIT License 5 votes vote down vote up
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,
        } 
Example 45
Project: tox   Author: tox-dev   File: test_result.py    MIT License 5 votes vote down vote up
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 
Example 46
Project: fuchsschwanz   Author: 20centaurifux   File: network.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def connection_made(self, transport):
        address = transport.get_extra_info("peername")

        self.__log.info("Client connected: %s:%d", address[0], address[1])

        cipher = transport.get_extra_info("cipher")
        tls = False

        if cipher:
            self.__log.info("Cipher: %s", cipher)
            tls = True

        self.__transport = transport
        self.__session_id = self.__session_store.new(ip=address[0],
                                                     host=socket.getfqdn(address[0]),
                                                     tls=tls,
                                                     t_recv=timer.Timer(),
                                                     t_alive=timer.Timer())
        self.__broker.add_session(self.__session_id, self.__handle_write__)
        self.__reputation.add_session(self.__session_id)
        self.__buffer = bytearray()
        self.__decoder = ltd.Decoder()
        self.__decoder.add_listener(self.__message_received__)
        self.__transform = Transform()
        self.__shutdown = False

        self.__log.debug("Session created successfully: %s", self.__session_id)

        self.__connections[self.__session_id] = self

        self.__write_protocol_info__() 
Example 47
Project: jerrybuild   Author: fboender   File: tools.py    GNU General Public License v3.0 5 votes vote down vote up
def mail(to, subject, msg, smtp_server="localhost"):
    """
    Email sender helper.
    """
    from_ = '{}@{}'.format(getpass.getuser(), socket.getfqdn())

    to_header = ', '.join(['<{}>'.format(t) for t in to])
    message = """To: <{}>
Subject: {}

{}
""".format(to_header, subject, msg)

    smtpObj = smtplib.SMTP(smtp_server)
    smtpObj.sendmail(from_, to, message) 
Example 48
Project: BlockchainPKI   Author: noahcoomer   File: node.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, hostname=None, addr="0.0.0.0", port=4848, bind=True, capath="~/.BlockchainPKI/validators/",
                 certfile="~/.BlockchainPKI/rootCA.pem", keyfile="~/.BlockchainPKI/rootCA.key"):
        '''
            Initialize the Node object

            :param str hostname: The fully qualified domain name
            :param str addr: The ip address to bind to
            :param int port: The port to bind to
            :param bool bind: Whether or not to bind a socket
            :param str capath: The path to the Validators CAs
        '''
        self.address = (addr, port)
        self.capath = capath.replace('~', os.environ['HOME'])

        if not bind:
            assert hostname != None, "Hostname must be specified when not binding"
            self.hostname = hostname
            self.address = (socket.gethostbyname(self.hostname), port)
        else:
            self.hostname = hostname or socket.getfqdn(socket.gethostname())
            self._init_net()

            self.certfile = certfile.replace('~', os.environ['HOME'])
            self.keyfile = keyfile.replace('~', os.environ['HOME'])
            self.receive_context = ssl.create_default_context(
                ssl.Purpose.CLIENT_AUTH)
            self.receive_context.load_cert_chain(self.certfile, self.keyfile) 
Example 49
Project: pilot2   Author: PanDAWMS   File: data.py    Apache License 2.0 5 votes vote down vote up
def detect_client_location(self):
        """
        Open a UDP socket to a machine on the internet, to get the local IPv4 and IPv6
        addresses of the requesting client.
        Try to determine the sitename automatically from common environment variables,
        in this order: SITE_NAME, ATLAS_SITE_NAME, OSG_SITE_NAME. If none of these exist
        use the fixed string 'ROAMING'.
        """

        ip = '0.0.0.0'
        try:
            import socket
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))
            ip = s.getsockname()[0]
        except Exception:
            pass

        ip6 = '::'
        try:
            s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
            s.connect(("2001:4860:4860:0:0:0:0:8888", 80))
            ip6 = s.getsockname()[0]
        except Exception:
            pass

        site = os.environ.get('PILOT_RUCIO_SITENAME', 'unknown')
#        site = os.environ.get('SITE_NAME',
#                              os.environ.get('ATLAS_SITE_NAME',
#                                             os.environ.get('OSG_SITE_NAME',
#                                                            'ROAMING')))

        return {'ip': ip,
                'ip6': ip6,
                'fqdn': socket.getfqdn(),
                'site': site} 
Example 50
Project: rucio   Author: rucio   File: utils.py    Apache License 2.0 5 votes vote down vote up
def detect_client_location():
    """
    Open a UDP socket to a machine on the internet, to get the local IPv4 and IPv6
    addresses of the requesting client.

    Try to determine the sitename automatically from common environment variables,
    in this order: SITE_NAME, ATLAS_SITE_NAME, OSG_SITE_NAME. If none of these exist
    use the fixed string 'ROAMING'.
    """

    ip = '0.0.0.0'
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
    except Exception:
        pass

    ip6 = '::'
    try:
        s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
        s.connect(("2001:4860:4860:0:0:0:0:8888", 80))
        ip6 = s.getsockname()[0]
    except Exception:
        pass

    site = os.environ.get('SITE_NAME',
                          os.environ.get('ATLAS_SITE_NAME',
                                         os.environ.get('OSG_SITE_NAME',
                                                        'ROAMING')))

    return {'ip': ip,
            'ip6': ip6,
            'fqdn': socket.getfqdn(),
            'site': site}