Python socket.getfqdn() Examples

The following are 40 code examples for showing how to use socket.getfqdn(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module socket , or try the search function .

Example 1
Project: neat-python   Author: CodeReclaimers   File: test_distributed.py    License: 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 2
Project: neat-python   Author: CodeReclaimers   File: distributed.py    License: 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 3
Project: verge3d-blender-addon   Author: Soft8Soft   File: utils.py    License: 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:

    <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 
Example 4
Project: misp42splunk   Author: remg427   File: utils.py    License: GNU Lesser 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:

    <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 
Example 5
Project: misp42splunk   Author: remg427   File: utils.py    License: GNU Lesser 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:

    <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 
Example 6
Project: sagemaker-xgboost-container   Author: aws   File: tracker.py    License: 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 7
Project: tox   Author: tox-dev   File: test_result.py    License: 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 8
Project: tf-yarn   Author: criteo   File: _internal.py    License: 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 9
Project: python-mysql-pool   Author: LuciferJack   File: connection.py    License: MIT License 6 votes vote down vote up
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 
Example 10
Project: aerospike-admin   Author: aerospike   File: node.py    License: Apache License 2.0 6 votes vote down vote up
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] 
Example 11
Project: meddle   Author: glmcdona   File: utils.py    License: MIT License 6 votes vote down vote up
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. 
Example 12
Project: meddle   Author: glmcdona   File: smtpd.py    License: MIT License 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 13
Project: ironpython2   Author: IronLanguages   File: utils.py    License: 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:

    <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. 
Example 14
Project: ironpython2   Author: IronLanguages   File: smtpd.py    License: 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 15
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: 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 16
Project: BinderFilter   Author: dxwu   File: utils.py    License: MIT License 6 votes vote down vote up
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. 
Example 17
Project: BinderFilter   Author: dxwu   File: smtpd.py    License: MIT License 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 18
Project: BinderFilter   Author: dxwu   File: test_socket.py    License: MIT License 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
            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))) 
Example 19
Project: Computable   Author: ktraunmueller   File: utils.py    License: MIT License 6 votes vote down vote up
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. 
Example 20
Project: oss-ftp   Author: aliyun   File: utils.py    License: MIT License 6 votes vote down vote up
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. 
Example 21
Project: oss-ftp   Author: aliyun   File: smtpd.py    License: MIT License 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: oss-ftp   Author: aliyun   File: test_socket.py    License: MIT License 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: network_tech   Author: heyglen   File: network.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 24
Project: InsightAgent   Author: insightfinder   File: collectdReportMetrics.py    License: 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 25
Project: zun   Author: openstack   File: compute_node_tracker.py    License: Apache License 2.0 5 votes vote down vote up
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 
Example 26
Project: Jtyoui   Author: jtyoui   File: gateway.py    License: MIT License 5 votes vote down vote up
def get_window_name():
    """获取window系统名"""
    return socket.getfqdn(socket.gethostname()) 
Example 27
Project: tox   Author: tox-dev   File: result.py    License: 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 28
Project: tox   Author: tox-dev   File: test_result.py    License: 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 29
Project: pagure   Author: Pagure   File: git_multimail_upstream.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, **kw):
        super(ComputeFQDNEnvironmentMixin, self).__init__(
            fqdn=socket.getfqdn(), **kw
        ) 
Example 30
Project: pythonpentest   Author: funkandwagnalls   File: hostdetails.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example 31
Project: BeatCop   Author: hassa   File: beatcop.py    License: MIT License 5 votes vote down vote up
def __init__(self, redis_, name, timeout=None, sleep=0.1):
        self.redis = redis_
        self.name = name
        self.timeout = timeout
        self.sleep = sleep
        # Instead of putting any old rubbish into the Lock's value, use our FQDN and PID
        self.value = "%s-%d" % (socket.getfqdn(), os.getpid())
        # rediscluster does not yet implement script management
        try:
            self._refresh_script = self.redis.register_script(self.lua_refresh)
        except rediscluster.exceptions.RedisClusterException:    # 'Method register_script is not possible to use in a redis cluster'
            pass 
Example 32
Project: rucio   Author: rucio   File: uploadclient.py    License: Apache License 2.0 5 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.client_location = detect_client_location()
        # if token should be used, use only JWT tokens
        self.auth_token = self.client.auth_token if len(self.client.auth_token.split(".")) == 3 else None
        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 33
Project: rucio   Author: rucio   File: utils.py    License: 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} 
Example 34
Project: rekall   Author: google   File: agent.py    License: GNU General Public License v2.0 5 votes vote down vote up
def from_current_system(cls, session=None):
        """Gets a Uname object populated from the current system"""
        uname = platform.uname()
        fqdn = socket.getfqdn()
        system = uname[0]
        architecture, _ = platform.architecture()
        if system == "Windows":
            service_pack = platform.win32_ver()[2]
            kernel = uname[3]  # 5.1.2600
            release = uname[2]  # XP, 2000, 7
            version = uname[3] + service_pack  # 5.1.2600 SP3, 6.1.7601 SP1
        elif system == "Darwin":
            kernel = uname[2]  # 12.2.0
            release = "OSX"  # OSX
            version = platform.mac_ver()[0]  # 10.8.2
        elif system == "Linux":
            kernel = uname[2]  # 3.2.5
            release = platform.linux_distribution()[0]  # Ubuntu
            version = platform.linux_distribution()[1]  # 12.04

        # Emulate PEP 425 naming conventions - e.g. cp27-cp27mu-linux_x86_64.
        pep425tag = "%s%s-%s-%s" % (pep425tags.get_abbr_impl(),
                                    pep425tags.get_impl_ver(),
                                    str(pep425tags.get_abi_tag()).lower(),
                                    pep425tags.get_platform())

        return cls.from_keywords(
            session=session,
            system=system,
            architecture=architecture,
            node=uname[1],
            release=release,
            version=version,
            machine=uname[4],              # x86, x86_64
            kernel=kernel,
            fqdn=fqdn,
            pep425tag=pep425tag,
        ) 
Example 35
Project: mysql_utils   Author: pinterest   File: get_recent_checksums.py    License: GNU General Public License v2.0 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description='MySQL checksum interface')
    parser.add_argument('-i',
                        '--instance',
                        help='Defaults to localhost:3306',
                        default=''.join((socket.getfqdn(), ':3306')),
                        required=True)
    parser.add_argument('-d',
                        '--db',
                        help="Restrict results to a single named db",
                        default=False)
    parser.add_argument('-t',
                        '--table',
                        help='Restrict results to a single table',
                        default=False)
    args = parser.parse_args()
    instance = host_utils.HostAddr(args.instance)

    checksums = get_checksums(instance, args.db)
    if not checksums:
        print "No data found!"
        sys.exit(1)

    format_str, line_length = generate_format_string(checksums)
    header = format_str.format(master_instance='Master',
                               instance='Replica',
                               reported_at='Date',
                               db='Database',
                               tbl='Table',
                               row_count='Row Count',
                               row_diffs='Diff Count',
                               checksum_status='Status')
    print header
    print '=' * line_length

    # now actually print the output.
    for checksum in checksums:
        if args.table is False or args.table == checksum['tbl']:
            checksum['reported_at'] = str(checksum['reported_at'])
            print format_str.format(**checksum) 
Example 36
Project: cascade-server   Author: mitre   File: settings.py    License: Apache License 2.0 5 votes vote down vote up
def setup(auto_defaults=False):
    placeholder = "<autogenerate>"

    with open('conf/defaults.yml', 'r') as f:
        defaults = yaml.load(f.read())

    defaults['server']['hostname'] = socket.getfqdn().lower()
    if auto_defaults:
        print("Automatically updated configuration settings for CASCADE based on defaults.yml")
        custom_settings = defaults
    else:
        print("Update configuration settings for CASCADE. Enter nothing to keep the default value")
        custom_settings = get_value(None, defaults)

    crypto = custom_settings['database']['crypto']

    if crypto['fernet'] == placeholder:
        crypto['fernet'] = cryptography.fernet.Fernet.generate_key()

    if crypto['key'] == placeholder:
        crypto['key'] = base64.b64encode(os.urandom(64))

    with open('conf/cascade.yml', 'w') as f:
        yaml.dump(custom_settings, f, explicit_start=True, indent=4, default_flow_style=False)

    print("\nInitializing database...")
    for filename in 'attack.bson', 'cascade-analytics.bson', 'default-sessions.bson':
        import_database_from_file('misc/{}'.format(filename)) 
Example 37
Project: PrivacyScore   Author: PrivacyScore   File: tasks.py    License: GNU General Public License v3.0 5 votes vote down vote up
def schedule_scan(scan_pk: int):
    """Prepare and schedule a scan."""
    scan = Scan.objects.get(pk=scan_pk)
    scan.start = timezone.now()
    scan.save()

    # Schedule next stage
    schedule_scan_stage(
        (getfqdn(), 'privacyscore.scanner.tasks.schedule_scan', [], {}),
        {},
        scan_pk) 
Example 38
Project: PrivacyScore   Author: PrivacyScore   File: tasks.py    License: GNU General Public License v3.0 5 votes vote down vote up
def run_test(test_suite: str, url: str, previous_results: dict) -> bool:
    """Run a single test against a single url."""
    test_parameters = TEST_PARAMETERS[test_suite]
    test_suite = AVAILABLE_TEST_SUITES[test_suite]
    try:
        with Timeout(settings.SCAN_SUITE_TIMEOUT_SECONDS):
            raw_data = test_suite.test_site(
                url, previous_results, **test_parameters)
            processed = test_suite.process_test_data(
                raw_data, previous_results, **test_parameters)
            return getfqdn(), test_suite.test_name, raw_data, processed
    except Exception as e:
        return ':'.join([getfqdn(), test_suite.test_name, traceback.format_exc()]) 
Example 39
Project: aerospike-admin   Author: aerospike   File: node.py    License: Apache License 2.0 5 votes vote down vote up
def _update_IP(self, address, port):
        if address not in self.dns_cache:
            self.dns_cache[address] = (
                socket.getaddrinfo(address, port, socket.AF_UNSPEC,
                                   socket.SOCK_STREAM)[0][4][0],
                getfqdn(address))

        self.ip, self.fqdn = self.dns_cache[address] 
Example 40
Project: GTDWeb   Author: lanbing510   File: utils.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_fqdn(self):
        if not hasattr(self, '_fqdn'):
            self._fqdn = socket.getfqdn()
        return self._fqdn