Python socket.gethostname() Examples

The following are code examples for showing how to use socket.gethostname(). 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: flexnet   Author: ressy   File: client.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, server, port=None):
        if port is None:
            port, server = server.split('@')
            port = int(port)

        self.server   = server # server hostname for TCP connections
        self.port     = port   # server port number for TCP connections
        self.debug    = False  # show raw binary sent and received
        self.verbose  = False  # show parsed messages received
        self.oldproto = None   # will be set later if server version < VER_NEW

        self.user    = os.environ.get('USER') or ''
        self.host    = socket.gethostname()
        self.vendor  = "" # empty to start, then vendor name
        self.tty     = '/dev/pts/1'
        self.pid     = str(os.getpid())
        self.arch    = 'x64_lsb' # OS/arch ("64-bit Linux Standard Base"?)
        self.version = (11,11) # "this" lmstat version

        self.connect()

    # Lower-level public methods for specific connection and request types 
Example 2
Project: pyblish-win   Author: pyblish   File: platform.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _node(default=''):

    """ Helper to determine the node name of this machine.
    """
    try:
        import socket
    except ImportError:
        # No sockets...
        return default
    try:
        return socket.gethostname()
    except socket.error:
        # Still not working...
        return default

# os.path.abspath is new in Python 1.5.2: 
Example 3
Project: pyblish-win   Author: pyblish   File: mailbox.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _create_tmp(self):
        """Create a file in the tmp subdirectory and open and return it."""
        now = time.time()
        hostname = socket.gethostname()
        if '/' in hostname:
            hostname = hostname.replace('/', r'\057')
        if ':' in hostname:
            hostname = hostname.replace(':', r'\072')
        uniq = "%s.M%sP%sQ%s.%s" % (int(now), int(now % 1 * 1e6), os.getpid(),
                                    Maildir._count, hostname)
        path = os.path.join(self._path, 'tmp', uniq)
        try:
            os.stat(path)
        except OSError, e:
            if e.errno == errno.ENOENT:
                Maildir._count += 1
                try:
                    return _create_carefully(path)
                except OSError, e:
                    if e.errno != errno.EEXIST:
                        raise 
Example 4
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 5
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def testSockName(self):
        # Testing getsockname()
        port = self._get_unused_port()
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.addCleanup(sock.close)
        sock.bind(("0.0.0.0", port))
        name = sock.getsockname()
        # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
        # it reasonable to get the host's addr in addition to 0.0.0.0.
        # At least for eCos.  This is required for the S/390 to pass.
        try:
            my_ip_addr = socket.gethostbyname(socket.gethostname())
        except socket.error:
            # Probably name lookup wasn't set up right; skip this test
            self.skipTest('name lookup failure')
        self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
        self.assertEqual(name[1], port) 
Example 6
Project: pyblish-win   Author: pyblish   File: test_import.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _test_UNC_path(self):
        with open(os.path.join(self.path, 'test_trailing_slash.py'), 'w') as f:
            f.write("testdata = 'test_trailing_slash'")
        # Create the UNC path, like \\myhost\c$\foo\bar.
        path = os.path.abspath(self.path)
        import socket
        hn = socket.gethostname()
        drive = path[0]
        unc = "\\\\%s\\%s$"%(hn, drive)
        unc += path[2:]
        try:
            os.listdir(unc)
        except OSError as e:
            if e.errno in (errno.EPERM, errno.EACCES):
                # See issue #15338
                self.skipTest("cannot access administrative share %r" % (unc,))
            raise
        sys.path.append(path)
        mod = __import__("test_trailing_slash")
        self.assertEqual(mod.testdata, 'test_trailing_slash')
        unload("test_trailing_slash") 
Example 7
Project: flasky   Author: RoseOu   File: control.py    MIT License 6 votes vote down vote up
def save(self):
        """Save the collected coverage data to the data file."""
        data_suffix = self.data_suffix
        if data_suffix is True:
            # If data_suffix was a simple true value, then make a suffix with
            # plenty of distinguishing information.  We do this here in
            # `save()` at the last minute so that the pid will be correct even
            # if the process forks.
            extra = ""
            if _TEST_NAME_FILE:
                f = open(_TEST_NAME_FILE)
                test_name = f.read()
                f.close()
                extra = "." + test_name
            data_suffix = "%s%s.%s.%06d" % (
                socket.gethostname(), extra, os.getpid(),
                random.randint(0, 999999)
                )

        self._harvest_data()
        self.data.write(suffix=data_suffix) 
Example 8
Project: core   Author: lifemapper   File: borgscribe.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, logger, dbUser=DbUser.Pipeline):
        """
        @summary Peruser constructor
        @param logger: logger for info and error reporting 
        @param dbUser: optional database user for connection
        """
        LMObject.__init__(self)
        self.log = logger
        self.hostname = socket.gethostname().lower()
        dbHost = DB_HOSTNAME
            
        if dbUser not in HL_NAME.keys():
            raise LMError('Unknown database user {}'.format(dbUser))
                
        self._borg = Borg(logger, dbHost, CONNECTION_PORT, dbUser, HL_NAME[dbUser])
                    
# ............................................................................ 
Example 9
Project: InsightAgent   Author: insightfinder   File: getmetrics_hadoop.py    Apache License 2.0 6 votes vote down vote up
def send_data(chunk_metric_data):
    """Sends metric data to InsightFinder backend"""
    send_data_time = time.time()
    # prepare data for metric streaming agent
    to_send_data_dict = dict()
    to_send_data_dict["metricData"] = json.dumps(chunk_metric_data)
    to_send_data_dict["licenseKey"] = agent_config_vars['licenseKey']
    to_send_data_dict["projectName"] = agent_config_vars['projectName']
    to_send_data_dict["userName"] = agent_config_vars['userName']
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    to_send_data_dict["samplingInterval"] = str(int(reporting_config_vars['reporting_interval'] * 60))
    to_send_data_dict["agentType"] = "custom"

    to_send_data_json = json.dumps(to_send_data_dict)
    logger.debug("TotalData: " + str(len(bytearray(to_send_data_json))))

    # send the data
    post_url = parameters['serverUrl'] + "/customprojectrawdata"
    response = requests.post(post_url, data=json.loads(to_send_data_json))
    if response.status_code == 200:
        logger.info(str(len(bytearray(to_send_data_json))) + " bytes of data are reported.")
    else:
        logger.info("Failed to send data.")
    logger.debug("--- Send data time: %s seconds ---" % (time.time() - send_data_time)) 
Example 10
Project: InsightAgent   Author: insightfinder   File: getmetrics_nfdump.py    Apache License 2.0 6 votes vote down vote up
def sendData(metricData):
    sendDataTime = time.time()
    # prepare data for metric streaming agent
    toSendDataDict = {}
    toSendDataDict["metricData"] = json.dumps(metricData)
    toSendDataDict["licenseKey"] = agentConfigVars['licenseKey']
    toSendDataDict["projectName"] = agentConfigVars['projectName']
    toSendDataDict["userName"] = agentConfigVars['userName']
    toSendDataDict["instanceName"] = socket.gethostname().partition(".")[0]
    toSendDataDict["samplingInterval"] = str(int(reportingConfigVars['reporting_interval'] * 60))
    toSendDataDict["agentType"] = "nfdump"

    toSendDataJSON = json.dumps(toSendDataDict)
    logger.debug("TotalData: " + str(len(bytearray(toSendDataJSON))))

    #send the data
    postUrl = parameters['serverUrl'] + "/customprojectrawdata"
    response = requests.post(postUrl, data=json.loads(toSendDataJSON))
    if response.status_code == 200:
        logger.info(str(len(bytearray(toSendDataJSON))) + " bytes of data are reported.")
        updateLastSentFiles(pcapFileList)
    else:
        logger.info("Failed to send data.")
    logger.debug("--- Send data time: %s seconds ---" % (time.time() - sendDataTime)) 
Example 11
Project: InsightAgent   Author: insightfinder   File: parseSendData.py    Apache License 2.0 6 votes vote down vote up
def send_data(metric_data):
    """ Sends parsed metric data to InsightFinder """
    send_data_time = time.time()
    # prepare data for metric streaming agent
    to_send_data_dict = dict()
    #for backend so this is the camel case in to_send_data_dict
    to_send_data_dict["metricData"] = json.dumps(metric_data)
    to_send_data_dict["licenseKey"] = config_vars['license_key']
    to_send_data_dict["projectName"] = config_vars['project_name']
    to_send_data_dict["userName"] = config_vars['user_name']
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    to_send_data_dict["samplingInterval"] = str(int(config_vars['sampling_interval'] * 60))
    to_send_data_dict["agentType"] = "LogStreaming"

    to_send_data_json = json.dumps(to_send_data_dict)

    # send the data
    post_url = parameters['server_url'] + "/customprojectrawdata"
    response = requests.post(post_url, data=json.loads(to_send_data_json))
    if response.status_code == 200:
        logger.info(str(len(bytearray(to_send_data_json))) + " bytes of data are reported.")
    else:
        logger.error("Failed to send data.")
    logger.info("--- Send data time: %s seconds ---" % (time.time() - send_data_time)) 
Example 12
Project: InsightAgent   Author: insightfinder   File: getlogs_Pufa.py    Apache License 2.0 6 votes vote down vote up
def send_data(metric_data):
    """ Sends parsed metric data to InsightFinder """
    send_data_time = time.time()
    # prepare data for metric streaming agent
    to_send_data_dict = dict()
    #for backend so this is the camel case in to_send_data_dict
    to_send_data_dict["metricData"] = json.dumps(metric_data)
    to_send_data_dict["licenseKey"] = config_vars['license_key']
    to_send_data_dict["projectName"] = config_vars['project_name']
    to_send_data_dict["userName"] = config_vars['user_name']
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    to_send_data_dict["samplingInterval"] = str(int(config_vars['sampling_interval'] * 60))
    to_send_data_dict["agentType"] = "LogStreaming"

    to_send_data_json = json.dumps(to_send_data_dict)

    # send the data
    post_url = parameters['server_url'] + "/customprojectrawdata"
    response = requests.post(post_url, data=json.loads(to_send_data_json))
    if response.status_code == 200:
        logger.info(str(len(bytearray(to_send_data_json))) + " bytes of data are reported.")
    else:
        logger.error("Failed to send data.")
    logger.info("--- Send data time: %s seconds ---" % (time.time() - send_data_time)) 
Example 13
Project: InsightAgent   Author: insightfinder   File: getmetrics_hbase.py    Apache License 2.0 6 votes vote down vote up
def send_data(chunk_metric_data):
    """Sends metric data to InsightFinder backend"""
    send_data_time = time.time()
    # prepare data for metric streaming agent
    to_send_data_dict = dict()
    to_send_data_dict["metricData"] = json.dumps(chunk_metric_data)
    to_send_data_dict["licenseKey"] = agent_config_vars['licenseKey']
    to_send_data_dict["projectName"] = agent_config_vars['projectName']
    to_send_data_dict["userName"] = agent_config_vars['userName']
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    to_send_data_dict["samplingInterval"] = str(int(reporting_config_vars['reporting_interval'] * 60))
    to_send_data_dict["agentType"] = "custom"

    to_send_data_json = json.dumps(to_send_data_dict)
    logger.debug("TotalData: " + str(len(bytearray(to_send_data_json))))

    # send the data
    post_url = parameters['serverUrl'] + "/customprojectrawdata"
    response = requests.post(post_url, data=json.loads(to_send_data_json))
    if response.status_code == 200:
        logger.info(str(len(bytearray(to_send_data_json))) + " bytes of data are reported.")
    else:
        logger.info("Failed to send data.")
    logger.debug("--- Send data time: %s seconds ---" % (time.time() - send_data_time)) 
Example 14
Project: InsightAgent   Author: insightfinder   File: getmetrics_opentsdb.py    Apache License 2.0 6 votes vote down vote up
def send_data(chunk_metric_data):
    send_data_time = time.time()
    # prepare data for metric streaming agent
    to_send_data_dict = dict()
    to_send_data_dict["metricData"] = json.dumps(chunk_metric_data)
    to_send_data_dict["licenseKey"] = agent_config_vars['licenseKey']
    to_send_data_dict["projectName"] = agent_config_vars['projectName']
    to_send_data_dict["userName"] = agent_config_vars['userName']
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    to_send_data_dict["samplingInterval"] = str(int(reporting_config_vars['reporting_interval'] * 60))
    to_send_data_dict["agentType"] = "custom"

    to_send_data_json = json.dumps(to_send_data_dict)
    logger.debug("TotalData: " + str(len(bytearray(to_send_data_json))))

    # send the data
    post_url = parameters['serverUrl'] + "/customprojectrawdata"
    response = requests.post(post_url, data=json.loads(to_send_data_json))
    if response.status_code == 200:
        logger.info(str(len(bytearray(to_send_data_json))) + " bytes of data are reported.")
    else:
        logger.info("Failed to send data.")
    logger.debug("--- Send data time: %s seconds ---" % (time.time() - send_data_time)) 
Example 15
Project: InsightAgent   Author: insightfinder   File: getmetrics_kafka.py    Apache License 2.0 6 votes vote down vote up
def sendData(metricData):
    sendDataTime = time.time()
    # prepare data for metric streaming agent
    toSendDataDict = {}
    toSendDataDict["metricData"] = json.dumps(metricData)
    toSendDataDict["licenseKey"] = agent_config_vars['licenseKey']
    toSendDataDict["projectName"] = agent_config_vars['projectName']
    toSendDataDict["userName"] = agent_config_vars['userName']
    toSendDataDict["instanceName"] = socket.gethostname().partition(".")[0]
    toSendDataDict["samplingInterval"] = str(int(agent_config_vars['samplingInterval']) * 60)
    toSendDataDict["agentType"] = "kafka"

    toSendDataJSON = json.dumps(toSendDataDict)
    # logger.debug("TotalData: " + str(len(bytearray(toSendDataJSON))))

    # send the data
    postUrl = parameters['serverUrl'] + "/customprojectrawdata"
    response = requests.post(postUrl, data=json.loads(toSendDataJSON))
    if response.status_code == 200:
        logger.info(str(len(bytearray(toSendDataJSON))) + " bytes of data are reported.")
        # updateLastSentFiles(pcapFileList)
    else:
        logger.info("Failed to send data.")
    # logger.debug("--- Send data time: %s seconds ---" % (time.time() - sendDataTime)) 
Example 16
Project: openhatch   Author: campbe13   File: case.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def managed(cls, hostname=None, caller=None):
        hostname = hostname or socket.gethostname()
        if caller:
            hostname = ".".join([get_full_cls_name(caller), hostname])
        else:
            hostname += str(cls.next_worker_id())
        worker = cls(hostname)
        worker.ensure_started()
        stack = traceback.format_stack()

        @atexit.register
        def _ensure_shutdown_once():
            if not worker._shutdown_called:
                say("-- Found worker not stopped at shutdown: %s\n%s" % (
                        worker.hostname,
                        "\n".join(stack)))
                worker.ensure_shutdown()

        return worker 
Example 17
Project: openhatch   Author: campbe13   File: __init__.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, connection=None, hostname=None, enabled=True,
            channel=None, buffer_while_offline=True, app=None,
            serializer=None):
        self.app = app_or_default(app)
        self.connection = connection
        self.channel = channel
        self.hostname = hostname or socket.gethostname()
        self.buffer_while_offline = buffer_while_offline
        self.mutex = threading.Lock()
        self.publisher = None
        self._outbound_buffer = deque()
        self.serializer = serializer or self.app.conf.CELERY_EVENT_SERIALIZER

        self.enabled = enabled
        if self.enabled:
            self.enable() 
Example 18
Project: openhatch   Author: campbe13   File: job.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, task_name, task_id, args, kwargs,
            on_ack=noop, retries=0, delivery_info=None, hostname=None,
            logger=None, eventer=None, eta=None, expires=None, app=None,
            taskset_id=None, chord=None, **opts):
        self.app = app_or_default(app)
        self.task_name = task_name
        self.task_id = task_id
        self.taskset_id = taskset_id
        self.retries = retries
        self.args = args
        self.kwargs = kwargs
        self.eta = eta
        self.expires = expires
        self.chord = chord
        self.on_ack = on_ack
        self.delivery_info = {} if delivery_info is None else delivery_info
        self.hostname = hostname or socket.gethostname()
        self.logger = logger or self.app.log.get_default_logger()
        self.eventer = eventer

        self.task = registry.tasks[self.task_name]
        self._store_errors = True
        if self.task.ignore_result:
            self._store_errors = self.task.store_errors_even_if_ignored 
Example 19
Project: pymoku   Author: liquidinstruments   File: __init__.py    MIT License 6 votes vote down vote up
def _ownership(self, t, flags):
        name = socket.gethostname()[:255]
        packet_data = struct.pack("<BBB", t, len(name) + 1, flags)
        packet_data += name.encode('ascii')
        with self._conn_lock:
            self._conn.send(packet_data)
            rep = self._conn.recv()

        t, plen, own = struct.unpack("<BBB", rep[:3])
        rep = rep[3:]

        last_seen = None
        if t == 0x41:
            last_seen = struct.unpack("<I", rep[:4])
            rep = rep[4:]

        owner = rep

        return own, owner, last_seen 
Example 20
Project: gnocchi   Author: gnocchixyz   File: metricd.py    Apache License 2.0 6 votes vote down vote up
def _configure(self):
        member_id = (
            "%s.%s.%s" % (socket.gethostname(),
                          self.worker_id,
                          # NOTE(jd) Still use a uuid here so we're
                          # sure there's no conflict in case of
                          # crash/restart
                          str(uuid.uuid4()))
        ).encode()
        self.coord = get_coordinator_and_start(member_id,
                                               self.conf.coordination_url)
        self.store = storage.get_driver(self.conf)
        self.incoming = incoming.get_driver(self.conf)
        self.index = indexer.get_driver(self.conf)
        self.chef = chef.Chef(self.coord, self.incoming,
                              self.index, self.store) 
Example 21
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 22
Project: fs_image   Author: facebookincubator   File: test_image_hostname.py    MIT License 5 votes vote down vote up
def test_container(self):
        # Ensure the hostname configuration was propagated inside the container
        self.assertEqual("test-hostname.com", socket.gethostname()) 
Example 23
Project: pyblish-win   Author: pyblish   File: mailbox.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _create_temporary(path):
    """Create a temp file based on path and open for reading and writing."""
    return _create_carefully('%s.%s.%s.%s' % (path, int(time.time()),
                                              socket.gethostname(),
                                              os.getpid())) 
Example 24
Project: programsynthesishunting   Author: flexgp   File: initialise_run.py    GNU General Public License v3.0 5 votes vote down vote up
def initialise_run_params(create_files):
    """
    Initialises all lists and trackers. Generates save folders and initial
    parameter files if debugging is not active.

    :return: Nothing
    """

    start = datetime.now()
    trackers.time_list.append(time())

    # Set random seed
    if params['RANDOM_SEED'] is None:
        params['RANDOM_SEED'] = int(start.microsecond)
    seed(params['RANDOM_SEED'])

    # Generate a time stamp for use with folder and file names.
    hms = "%02d%02d%02d" % (start.hour, start.minute, start.second)
    params['TIME_STAMP'] = "_".join([gethostname(),
                                     str(start.year)[2:],
                                     str(start.month),
                                     str(start.day),
                                     hms,
                                     str(start.microsecond),
                                     str(getpid()),
                                     str(params['RANDOM_SEED'])])
    if not params['SILENT']:
        print("\nStart:\t", start, "\n")

    # Generate save folders and files
    if params['DEBUG']:
        print("Seed:\t", params['RANDOM_SEED'], "\n")
    elif create_files:
        generate_folders_and_files() 
Example 25
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 5 votes vote down vote up
def __init__(self, path, threaded=True, timeout=None):
        """
        >>> lock = LockBase('somefile')
        >>> lock = LockBase('somefile', threaded=False)
        """
        super(LockBase, self).__init__(path)
        self.lock_file = os.path.abspath(path) + ".lock"
        self.hostname = socket.gethostname()
        self.pid = os.getpid()
        if threaded:
            t = threading.current_thread()
            # Thread objects in Python 2.4 and earlier do not have ident
            # attrs.  Worm around that.
            ident = getattr(t, "ident", hash(t))
            self.tname = "-%x" % (ident & 0xffffffff)
        else:
            self.tname = ""
        dirname = os.path.dirname(self.lock_file)

        # unique name is mostly about the current process, but must
        # also contain the path -- otherwise, two adjacent locked
        # files conflict (one file gets locked, creating lock-file and
        # unique file, the other one gets locked, creating lock-file
        # and overwriting the already existing lock-file, then one
        # gets unlocked, deleting both lock-file and unique file,
        # finally the last lock errors out upon releasing.
        self.unique_name = os.path.join(dirname,
                                        "%s%s.%s%s" % (self.hostname,
                                                       self.tname,
                                                       self.pid,
                                                       hash(self.path)))
        self.timeout = timeout 
Example 26
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: _netscaler.py    MIT License 5 votes vote down vote up
def main():

    module = AnsibleModule(
        argument_spec=dict(
            nsc_host=dict(type='str', required=True),
            nsc_protocol=dict(type='str', default='https'),
            user=dict(type='str', required=True),
            password=dict(type='str', required=True, no_log=True),
            action=dict(type='str', default='enable', choices=['disable', 'enable']),
            name=dict(type='str', default=socket.gethostname()),
            type=dict(type='str', default='server', choices=['server', 'service']),
            validate_certs=dict(type='bool', default=True),
        ),
    )

    rc = 0
    try:
        rc, result = core(module)
    except Exception as e:
        module.fail_json(msg=to_native(e), exception=traceback.format_exc())

    if rc != 0:
        module.fail_json(rc=rc, msg=result)
    else:
        result['changed'] = True
        module.exit_json(**result) 
Example 27
Project: radius-1xtest   Author: shanghai-edu   File: utils.py    Apache License 2.0 5 votes vote down vote up
def radius_challenge(username, password, host, secret, port, nasip, debug):
        hostname = gethostname()
        dict_path = sys.path[0] + "/lib/dicts/dictionary"
        radius = Client(server = host, secret = secret, authport = port, dict = Dictionary(dict_path))
        request = radius.CreateAuthPacket(code = packet.AccessRequest)
        if debug:
                print "[DEBUG] assembling packet attributes"
        request["User-Name"] = username
        request["NAS-IP-Address"] = nasip
        request["NAS-Identifier"] = hostname
        if debug:
                print "[DEBUG] auth method: mscharpv2"
        auth = mschap2.MSCHAP2()
        authAttrs = {}
        authAttrs = auth.getAuthAttrs(username, password)
        for key in authAttrs.keys():
                request[key] = authAttrs[key]
        if debug:
                print "[DEBUG] dumping request attributes..."
                for key in request.keys():
                        print "[DEBUG]\t\t %s : %s" % (key,request[key])
        tsStart = time()
        try:
                reply = radius.SendPacket(request)
        except packet.PacketError,e:
                if debug:
                        print e
                print "CRITICAL: Timeout sending Access-Request"
                return False 
Example 28
Project: sic   Author: Yanixos   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, path, threaded=True, timeout=None):
        """
        >>> lock = LockBase('somefile')
        >>> lock = LockBase('somefile', threaded=False)
        """
        super(LockBase, self).__init__(path)
        self.lock_file = os.path.abspath(path) + ".lock"
        self.hostname = socket.gethostname()
        self.pid = os.getpid()
        if threaded:
            t = threading.current_thread()
            # Thread objects in Python 2.4 and earlier do not have ident
            # attrs.  Worm around that.
            ident = getattr(t, "ident", hash(t))
            self.tname = "-%x" % (ident & 0xffffffff)
        else:
            self.tname = ""
        dirname = os.path.dirname(self.lock_file)

        # unique name is mostly about the current process, but must
        # also contain the path -- otherwise, two adjacent locked
        # files conflict (one file gets locked, creating lock-file and
        # unique file, the other one gets locked, creating lock-file
        # and overwriting the already existing lock-file, then one
        # gets unlocked, deleting both lock-file and unique file,
        # finally the last lock errors out upon releasing.
        self.unique_name = os.path.join(dirname,
                                        "%s%s.%s%s" % (self.hostname,
                                                       self.tname,
                                                       self.pid,
                                                       hash(self.path)))
        self.timeout = timeout 
Example 29
Project: PathDump   Author: PathDump   File: helperapi.py    Apache License 2.0 5 votes vote down vote up
def getCurNodeID ():
    return socket.gethostname() 
    #return ni.ifaddresses('eth0')[2][0]['addr'] 
Example 30
Project: flask-observability   Author: adimian   File: __init__.py    MIT License 5 votes vote down vote up
def __init__(self, app=None, hostname=None, ignored_routes=("static",)):
        self.hostname = hostname or socket.gethostname()
        self.app = app
        self.ignored_routes = ignored_routes
        self._client = None

        if app is not None:
            self.init_app(app)

        self.outgoing = defaultdict(list) 
Example 31
Project: i-portalen   Author: I-sektionen   File: feed_tags.py    MIT License 5 votes vote down vote up
def print_event(event):
    def _descr(e):
        s1 = e.lead
        s2 = _(" Eventet finns på: www.i-portalen.se") + e.get_absolute_url()
        return s1 + s2
    t_format = "%Y%m%dT%H%M%SZ"  # Formating style used by the ics-file format. (Z means UTC).
    s = "".join(["BEGIN:VEVENT\n",
                 "DTSTART:{start}\n",
                 "DTEND:{end}\n",
                 "SUMMARY:{summary}\n",
                 "LOCATION:{location}\n",
                 "DESCRIPTION:{desc}\n",
                 "UID:{uid}\n",
                 "DTSTAMP:{timestamp}\n",
                 "LAST-MODIFIED:{modified}\n"
                 "URL:{url}\n",
                 "END:VEVENT\n"]).format(
        # This timezone thing does not work. Now is it converted manually by subtracting one hour to UTC.
 #       start=event.start.astimezone(timezone('Europe/London')).strftime(t_format),  # Switched to UTC instead.
 #       end=event.end.astimezone(timezone('Europe/London')).strftime(t_format),  # Switched to UTC instead.
        start=(event.start).strftime(t_format),
        end=(event.end).strftime(t_format),
        summary=event.headline,
        location=event.location,
        desc=_descr(event),
        url="www.i-portalen.se" + event.get_absolute_url(),
        uid="IPORTALEN_DJANGO_1337" + str(event.pk) + "@" + socket.gethostname(),  # Unique identifier
        modified=event.modified.strftime(t_format),
        timestamp=event.created.strftime(t_format))

    return s 
Example 32
Project: zabbix   Author: xiaomatech   File: rabbitmq-api.py    MIT License 5 votes vote down vote up
def __init__(self,
                 user_name='guest',
                 password='guest',
                 host_name='',
                 protocol='http',
                 port=15672,
                 conf='/etc/zabbix/zabbix_agentd.conf',
                 senderhostname=None):
        self.user_name = user_name
        self.password = password
        self.host_name = host_name or socket.gethostname()
        self.protocol = protocol
        self.port = port
        self.conf = conf or '/etc/zabbix/zabbix_agentd.conf'
        self.senderhostname = senderhostname if senderhostname else host_name 
Example 33
Project: AshsSDK   Author: thehappydinoa   File: __init__.py    MIT License 5 votes vote down vote up
def __init__(self, path, threaded=True, timeout=None):
        """
        >>> lock = LockBase('somefile')
        >>> lock = LockBase('somefile', threaded=False)
        """
        super(LockBase, self).__init__(path)
        self.lock_file = os.path.abspath(path) + ".lock"
        self.hostname = socket.gethostname()
        self.pid = os.getpid()
        if threaded:
            t = threading.current_thread()
            # Thread objects in Python 2.4 and earlier do not have ident
            # attrs.  Worm around that.
            ident = getattr(t, "ident", hash(t))
            self.tname = "-%x" % (ident & 0xffffffff)
        else:
            self.tname = ""
        dirname = os.path.dirname(self.lock_file)

        # unique name is mostly about the current process, but must
        # also contain the path -- otherwise, two adjacent locked
        # files conflict (one file gets locked, creating lock-file and
        # unique file, the other one gets locked, creating lock-file
        # and overwriting the already existing lock-file, then one
        # gets unlocked, deleting both lock-file and unique file,
        # finally the last lock errors out upon releasing.
        self.unique_name = os.path.join(dirname,
                                        "%s%s.%s%s" % (self.hostname,
                                                       self.tname,
                                                       self.pid,
                                                       hash(self.path)))
        self.timeout = timeout 
Example 34
Project: AshsSDK   Author: thehappydinoa   File: opsworks.py    MIT License 5 votes vote down vote up
def determine_details(self, args):
        """
        Determine details (like the address to connect to and the hostname to
        use) from the given arguments and the retrieved data.

        Provides `self._use_address` (if not provided already),
        `self._use_hostname` and `self._name_for_iam`.
        """

        # determine the address to connect to
        if not self._use_address:
            if args.local:
                pass
            elif args.infrastructure_class == 'ec2':
                if 'PublicIpAddress' in self._ec2_instance:
                    self._use_address = self._ec2_instance['PublicIpAddress']
                elif 'PrivateIpAddress' in self._ec2_instance:
                    LOG.warn(
                        "Instance does not have a public IP address. Trying "
                        "to use the private address to connect.")
                    self._use_address = self._ec2_instance['PrivateIpAddress']
                else:
                    # Should never happen
                    raise ValueError(
                        "The instance does not seem to have an IP address.")
            elif args.infrastructure_class == 'on-premises':
                self._use_address = args.target

        # determine the names to use
        if args.hostname:
            self._use_hostname = args.hostname
            self._name_for_iam = args.hostname
        elif args.local:
            self._use_hostname = None
            self._name_for_iam = socket.gethostname()
        else:
            self._use_hostname = None
            self._name_for_iam = args.target 
Example 35
Project: InsightAgent   Author: insightfinder   File: getincident_kafka.py    Apache License 2.0 5 votes vote down vote up
def send_data(metric_data):
    """ Sends parsed metric data to InsightFinder """
    send_data_time = time.time()
    # prepare data for metric streaming agent
    to_send_data_dict = dict()
    to_send_data_dict["incidentData"] = json.dumps(metric_data)
    to_send_data_dict["licenseKey"] = agent_config_vars['licenseKey']
    if parameters['project'] is None:
        to_send_data_dict["projectName"] = agent_config_vars['projectName']
    else:
        to_send_data_dict["projectName"] = parameters['project']
    to_send_data_dict["userName"] = agent_config_vars['userName']
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    to_send_data_dict["samplingInterval"] = agent_config_vars['samplingInterval']
    to_send_data_dict["agentType"] = "LogStreaming"

    to_send_data_json = json.dumps(to_send_data_dict)

    # send the data
    post_url = parameters['serverUrl'] + "/incidentdatareceive"
    response = requests.post(post_url, data=json.loads(to_send_data_json))
    if response.status_code == 200:
        logger.info(str(len(bytearray(to_send_data_json))) + " bytes of data are reported.")
    else:
        logger.info("Failed to send data.")
    logger.debug("--- Send data time: %s seconds ---" % (time.time() - send_data_time)) 
Example 36
Project: InsightAgent   Author: insightfinder   File: getlogs_kafka.py    Apache License 2.0 5 votes vote down vote up
def send_data(metric_data):
    """ Sends parsed metric data to InsightFinder """
    send_data_time = time.time()
    # prepare data for metric streaming agent
    to_send_data_dict = dict()
    to_send_data_dict["metricData"] = json.dumps(metric_data)
    to_send_data_dict["licenseKey"] = agent_config_vars['licenseKey']
    if parameters['project'] is None:
        to_send_data_dict["projectName"] = agent_config_vars['projectName']
    else:
        to_send_data_dict["projectName"] = parameters['project']
    to_send_data_dict["userName"] = agent_config_vars['userName']
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    to_send_data_dict["samplingInterval"] = str(int(agent_config_vars['samplingInterval'] * 60))
    to_send_data_dict["agentType"] = "LogStreaming"

    to_send_data_json = json.dumps(to_send_data_dict)
    # logger.debug("TotalData: " + str(len(bytearray(to_send_data_json))))
    # logger.debug("Data: " + str(to_send_data_json))

    # send the data
    post_url = parameters['serverUrl'] + "/customprojectrawdata"
    response = requests.post(post_url, data=json.loads(to_send_data_json))
    if response.status_code == 200:
        logger.info(str(len(bytearray(to_send_data_json))) + " bytes of data are reported.")
    else:
        logger.info("Failed to send data.")
    logger.debug("--- Send data time: %s seconds ---" % (time.time() - send_data_time)) 
Example 37
Project: InsightAgent   Author: insightfinder   File: getmetrics_kvm.py    Apache License 2.0 5 votes vote down vote up
def updateHeaderForHost(headerList):
    hostname = socket.gethostname().partition(".")[0]
    hostMetrics = ["FreeMemory", "CPUCount", "CPUUsage_Kernel", "CPUUsage_Idle", "CPUUsage_User", "CPUUsage_IOWait"]
    headerList.append("timestamp")
    for hostMetric in hostMetrics:
        headerList.append(hostMetric + "[" + hostname + "]:" + str(getIndexForColName(hostMetric))) 
Example 38
Project: InsightAgent   Author: insightfinder   File: insightfinder.py    Apache License 2.0 5 votes vote down vote up
def append(self, metric):
        """
        Flushes the metrics provided to InsightFinder.
        Parameters:
        - `metric` : A string entry with format key|value|timestamp.
        """
        if not metric and metric.count("|") != 2:
            return
        hostname = socket.gethostname()

        if len(metric) != 0:
            metric_split = metric.split("|")
            metric_key = self.normalize_key(metric_split[0])
            metric_value = metric_split[1]
            timestamp = int(metric_split[2])

            hostname = self._get_detail_from_metric(metric_key, self.host_range).replace("_", "-")
            metric_name = self._get_detail_from_metric(metric_key, self.metric_name_range)

            if timestamp in self.metrics_map:
                value_map = self.metrics_map[timestamp]
            else:
                value_map = {}

            value_map[metric_name + '[' + hostname + ']:' +
                      str(self._get_grouping_id(metric_name))] = metric_value
            self.temp_group_id += 1
            self.metrics_map[timestamp] = value_map 
Example 39
Project: InsightAgent   Author: insightfinder   File: insightfinder.py    Apache License 2.0 5 votes vote down vote up
def _send_data(self, metric_data):
        if not metric_data or len(metric_data) == 0:
            self.logger.warning("No data to send for this flush.")
            return

        send_data_time = time.time()

        # prepare data for metric streaming agent
        to_send_data_dict = {}
        to_send_data_dict["metricData"] = json.dumps(metric_data)
        to_send_data_dict["licenseKey"] = self.license_key
        to_send_data_dict["projectName"] = self.project_name
        to_send_data_dict["userName"] = self.username
        to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[
            0]
        to_send_data_dict["samplingInterval"] = str(self.sampling_interval)
        to_send_data_dict["agentType"] = "custom"

        to_send_data_json = json.dumps(to_send_data_dict)
        self.logger.debug(
            "TotalData: " + str(len(bytearray(to_send_data_json))) + "bytes")

        # send the data
        postUrl = self.url + "/customprojectrawdata"
        response = requests.post(postUrl, data=json.loads(to_send_data_json))
        if response.status_code == 200:
            self.logger.info(str(len(bytearray(to_send_data_json))
                                 ) + " bytes of data are reported.")
        else:
            self.logger.exception("Failed to send data.")
            raise IOError("Failed to send request to " + postUrl)
        self.logger.debug("Send data time: %s seconds " %
                          (time.time() - send_data_time)) 
Example 40
Project: InsightAgent   Author: insightfinder   File: getmetrics_zipkin.py    Apache License 2.0 5 votes vote down vote up
def initialize_api_post_data():
    to_send_data_dict = dict()
    to_send_data_dict["licenseKey"] = if_config_vars['licenseKey']
    to_send_data_dict["projectName"] = if_config_vars['projectName']
    to_send_data_dict["userName"] = if_config_vars['userName']
    to_send_data_dict["samplingInterval"] = str(int(if_config_vars['samplingInterval']) * 60)
    to_send_data_dict["instanceName"] = socket.gethostname().partition(".")[0]
    return to_send_data_dict 
Example 41
Project: storjnode   Author: StorjOld   File: util.py    MIT License 5 votes vote down vote up
def get_inet_facing_ip():
    # source http://stackoverflow.com/a/1267524/90351
    try:
        return [l for l in ([ip for ip in socket.gethostbyname_ex(
            socket.gethostname())[2] if not ip.startswith("127.")][:1],
            [[(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close())
                for s in [socket.socket(
                    socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0]
    except:  # pragma: no cover
        # inet not reachable
        return None  # pragma: no cover 
Example 42
Project: cis   Author: mozilla-iam   File: test_log.py    Mozilla Public License 2.0 5 votes vote down vote up
def setup_class(self):
        self.logger = logging.getLogger()

        handler = logging.StreamHandler()
        handler.setFormatter(cis_logger.JsonFormatter(extra={"hello": "world", "hostname": socket.gethostname()}))

        self.logger.addHandler(handler)
        self.logger.setLevel(logging.INFO) 
Example 43
Project: cis   Author: mozilla-iam   File: handler.py    Mozilla Public License 2.0 5 votes vote down vote up
def setup_logging():
    logger = logging.getLogger()
    for h in logger.handlers:
        logger.removeHandler(h)
    h = logging.StreamHandler(sys.stdout)
    h.setFormatter(cis_logger.JsonFormatter(extra={"hostname": socket.gethostname()}))
    logger.addHandler(h)
    logger.setLevel(logging.INFO)
    return logger 
Example 44
Project: cis   Author: mozilla-iam   File: handler.py    Mozilla Public License 2.0 5 votes vote down vote up
def setup_logging():
    logger = logging.getLogger()
    for h in logger.handlers:
        logger.removeHandler(h)
    h = logging.StreamHandler(sys.stdout)
    h.setFormatter(cis_logger.JsonFormatter(extra={"hostname": socket.gethostname()}))
    logger.addHandler(h)
    logger.setLevel(logging.INFO)

    # Quiet botocore verbose logging...
    logging.getLogger("botocore").setLevel(logging.WARNING)
    return logger 
Example 45
Project: cis   Author: mozilla-iam   File: handler.py    Mozilla Public License 2.0 5 votes vote down vote up
def setup_logging():
    logger = logging.getLogger()
    for h in logger.handlers:
        logger.removeHandler(h)
    h = logging.StreamHandler(sys.stdout)
    h.setFormatter(cis_logger.JsonFormatter(extra={"hostname": socket.gethostname()}))
    logger.addHandler(h)
    logger.setLevel(logging.INFO)
    return logger 
Example 46
Project: cis   Author: mozilla-iam   File: handler.py    Mozilla Public License 2.0 5 votes vote down vote up
def setup_logging():
    logger = logging.getLogger()
    for h in logger.handlers:
        logger.removeHandler(h)
    h = logging.StreamHandler(sys.stdout)
    h.setFormatter(cis_logger.JsonFormatter(extra={"hostname": socket.gethostname()}))
    logger.addHandler(h)
    logger.setLevel(logging.INFO)
    return logger 
Example 47
Project: cis   Author: mozilla-iam   File: handler.py    Mozilla Public License 2.0 5 votes vote down vote up
def setup_logging():
    logger = logging.getLogger()
    for h in logger.handlers:
        logger.removeHandler(h)
    h = logging.StreamHandler(sys.stdout)
    h.setFormatter(cis_logger.JsonFormatter(extra={"hostname": socket.gethostname()}))
    logger.addHandler(h)
    logger.setLevel(logging.INFO)
    return logger 
Example 48
Project: cis   Author: mozilla-iam   File: handler.py    Mozilla Public License 2.0 5 votes vote down vote up
def setup_logging():
    logger = logging.getLogger()
    for h in logger.handlers:
        logger.removeHandler(h)
    h = logging.StreamHandler(sys.stdout)
    h.setFormatter(cis_logger.JsonFormatter(extra={"hostname": socket.gethostname()}))
    logger.addHandler(h)
    logger.setLevel(logging.INFO)
    return logger 
Example 49
Project: cis   Author: mozilla-iam   File: handler.py    Mozilla Public License 2.0 5 votes vote down vote up
def setup_logging():
    logger = logging.getLogger()
    for h in logger.handlers:
        logger.removeHandler(h)
    h = logging.StreamHandler(sys.stdout)
    h.setFormatter(cis_logger.JsonFormatter(extra={"hostname": socket.gethostname()}))
    logger.addHandler(h)
    logger.setLevel(logging.INFO)
    return logger 
Example 50
Project: cis   Author: mozilla-iam   File: handler.py    Mozilla Public License 2.0 5 votes vote down vote up
def setup_logging():
    logger = logging.getLogger()
    for h in logger.handlers:
        logger.removeHandler(h)
    h = logging.StreamHandler(sys.stdout)
    h.setFormatter(cis_logger.JsonFormatter(extra={"hostname": socket.gethostname()}))
    logger.addHandler(h)
    logger.setLevel(logging.INFO)
    return logger