Python get uptime

35 Python code examples are found related to " get uptime". 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.
Example 1
Source File: general.py    From spirit with MIT License 8 votes vote down vote up
def get_bot_uptime(self, *, brief=False):
        now = datetime.utcnow()
        delta = now - self.bot.uptime
        hours, remainder = divmod(int(delta.total_seconds()), 3600)
        minutes, seconds = divmod(remainder, 60)
        days, hours = divmod(hours, 24)

        if not brief:
            if days:
                fmt = '{d} days, {h} hours, {m} minutes, and {s} seconds'
            else:
                fmt = '{h} hours, {m} minutes, and {s} seconds'
        else:
            fmt = '{h}h {m}m {s}s'
            if days:
                fmt = '{d}d ' + fmt

        return fmt.format(d=days, h=hours, m=minutes, s=seconds) 
Example 2
Source File: hostops.py    From compute-hyperv with Apache License 2.0 7 votes vote down vote up
def get_host_uptime(self):
        """Returns the host uptime."""

        tick_count64 = self._hostutils.get_host_tick_count64()

        # format the string to match libvirt driver uptime
        # Libvirt uptime returns a combination of the following
        # - current host time
        # - time since host is up
        # - number of logged in users
        # - cpu load
        # Since the Windows function GetTickCount64 returns only
        # the time since the host is up, returning 0s for cpu load
        # and number of logged in users.
        # This is done to ensure the format of the returned
        # value is same as in libvirt
        return "%s up %s,  0 users,  load average: 0, 0, 0" % (
                   str(time.strftime("%H:%M:%S")),
                   str(datetime.timedelta(milliseconds=int(tick_count64)))) 
Example 3
Source File: control.py    From stem with GNU Lesser General Public License v3.0 6 votes vote down vote up
def get_uptime(self, default: Any = UNDEFINED) -> float:
    """
    get_uptime(default = UNDEFINED)

    Provides the duration in seconds that tor has been running.

    .. versionadded:: 1.8.0

    :param default: response if the query fails

    :returns: **float** for the number of seconds tor has been running

    :raises: **ValueError** if unable to determine the uptime and no default
      was provided
    """

    return time.time() - self.get_start_time() 
Example 4
Source File: fritzbox_uptime.py    From fritzbox-munin with GNU General Public License v2.0 6 votes vote down vote up
def get_uptime():
    """get the current uptime"""

    server = os.environ['fritzbox_ip']
    password = os.environ['fritzbox_password']

    session_id = fh.get_session_id(server, password)
    xhr_data = fh.get_xhr_content(server, session_id, PAGE)
    data = json.loads(xhr_data)
    for d in data['data']['drain']:
        if 'aktiv' in d['statuses']:
            matches = re.finditer(pattern, d['statuses'])
            if matches:
                hours = 0.0
                for m in matches:
                    if m.group(2) == dayLoc[locale]:
                        hours += 24 * int(m.group(1))
                    if m.group(2) == hourLoc[locale]:
                        hours += int(m.group(1))
                    if m.group(2) == minutesLoc[locale]:
                        hours += int(m.group(1)) / 60.0
                uptime = hours / 24
                print("uptime.value %.2f" % uptime) 
Example 5
Source File: cacher.py    From Cacher with Apache License 2.0 6 votes vote down vote up
def get_uptime():
    try:
        cmd = ['/usr/bin/uptime']
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        output, err = proc.communicate()
        splitout = str.split(output)
        uptimeamount = splitout[2]
        # Uptime Type to use if units are "less than days"
        uptimetype = splitout[3].replace(',', '')
        if uptimeamount[-1:]==',':
            # Last char is a comma; this likely indicates that the
            # `uptimetype` is in hours and not in a "greater" unit
            uptimeamount = uptimeamount[:-1] # get rid of the comma at the end
            uptimeamount = uptimeamount.split(':')
            hourtype = ' hour, ' if uptimeamount[0]==1 else ' hours, '
            uptimeamount = uptimeamount[0] + hourtype + uptimeamount[1]
            # `uptimetype` to use if main units are in hours and minutes,
            # which is not the best way to handle this... but it works.
            uptimetype = 'minutes'
        return '%s %s' % (uptimeamount, uptimetype)
    except Exception:
        return None 
Example 6
Source File: utils_misc.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def get_uptime(session=None):
    """
    Get the uptime of system in secs

    :param session: VM session or remote session object, None for host

    :return: uptime of system in float, None on error
    """
    cmd = "cat /proc/uptime"
    if session:
        uptime = session.cmd_output(cmd)
    else:
        try:
            uptime = process.run(cmd, shell=True).stdout_text
        except process.CmdError:
            return None
    return float(uptime.split()[0]) 
Example 7
Source File: meta.py    From discordbot.py with MIT License 6 votes vote down vote up
def get_bot_uptime(self, *, brief=False):
        now = datetime.datetime.utcnow()
        delta = now - self.bot.uptime
        hours, remainder = divmod(int(delta.total_seconds()), 3600)
        minutes, seconds = divmod(remainder, 60)
        days, hours = divmod(hours, 24)

        if not brief:
            if days:
                fmt = '{d} days, {h} hours, {m} minutes, and {s} seconds'
            else:
                fmt = '{h} hours, {m} minutes, and {s} seconds'
        else:
            fmt = '{h}h {m}m {s}s'
            if days:
                fmt = '{d}d ' + fmt

        return fmt.format(d=days, h=hours, m=minutes, s=seconds) 
Example 8
Source File: check_uptime_by_ssh.py    From check-linux-by-ssh with MIT License 5 votes vote down vote up
def get_uptime(client):
    # We are looking for a line like 
    #5265660.84 4856671.67
    raw = r"""cat /proc/uptime"""
    stdin, stdout, stderr = client.exec_command(raw)
    line = [l for l in stdout][0].strip()
    
    uptime, _ = tuple([int(float(v)) for v in line.split(' ')])

    # Before return, close the client
    client.close()

    return uptime 
Example 9
Source File: sysinfo.py    From lpts with GNU General Public License v2.0 5 votes vote down vote up
def get_uptime():
    """
    :return: return the uptime of system in secs in float
    in error case return 'None'
    """

    cmd = "/bin/cat /proc/uptime"
    (status, output) = commands.getstatusoutput(cmd)
    if status == 0:
        return output.split()[0]
    else:
        return None 
Example 10
Source File: util.py    From satellite-sanity with GNU General Public License v3.0 5 votes vote down vote up
def get_days_uptime(uptime):
  """Return number of days from uptime"""
  # FIXME: what happens when system have uptime in years?
  # Maybe http://bytes.com/topic/python/answers/36189-uptime-unix#td_post_135199
  ###logger.debug("Going to parse %s" % uptime)
  uptime_split = uptime.strip().split(' ')
  if uptime_split[3] == 'days,':
    return int(uptime_split[2])
  elif uptime_split[3] == 'day,':
    return int(uptime_split[2])
  else:
    return 0 
Example 11
Source File: sat5_taskomatic_running.py    From satellite-sanity with GNU General Public License v3.0 5 votes vote down vote up
def get_uptime(data):
    """
    Return the number of days the machine has been up
    """
    return {'UPTIME_DAYS': int(get_days_uptime(data['uptime'][0]))} 
Example 12
Source File: metrics.py    From temboard-agent with PostgreSQL License 5 votes vote down vote up
def get_pg_uptime(self,):
        query = """
SELECT date_trunc('seconds', NOW() - pg_postmaster_start_time()) AS uptime
        """
        self.conn.execute(query)
        return list(self.conn.get_rows())[0]['uptime'] 
Example 13
Source File: unicorn_binance_websocket_api_manager.py    From unicorn-binance-websocket-api with MIT License 5 votes vote down vote up
def get_human_uptime(uptime):
        """
        Convert a timespan of seconds into hours, days, ...

        :param uptime: Uptime in seconds
        :type uptime: int
        :return:
        """
        if uptime > (60 * 60 * 24):
            uptime_days = int(uptime / (60 * 60 * 24))
            uptime_hours = int(((uptime - (uptime_days * (60 * 60 * 24))) / (60 * 60)))
            uptime_minutes = int((uptime - ((uptime_days * (60 * 60 * 24)) + (uptime_hours * 60 * 60))) / 60)
            uptime_seconds = int(
                uptime - ((uptime_days * (60 * 60 * 24)) + ((uptime_hours * (60 * 60)) + (uptime_minutes * 60))))
            uptime = str(uptime_days) + "d:" + str(uptime_hours) + "h:" + str(int(uptime_minutes)) + "m:" + str(
                int(uptime_seconds)) + "s"
        elif uptime > (60 * 60):
            uptime_hours = int(uptime / (60 * 60))
            uptime_minutes = int((uptime - (uptime_hours * (60 * 60))) / 60)
            uptime_seconds = int(uptime - ((uptime_hours * (60 * 60)) + (uptime_minutes * 60)))
            uptime = str(uptime_hours) + "h:" + str(int(uptime_minutes)) + "m:" + str(int(uptime_seconds)) + "s"
        elif uptime > 60:
            uptime_minutes = int(uptime / 60)
            uptime_seconds = uptime - uptime_minutes * 60
            uptime = str(uptime_minutes) + "m:" + str(int(uptime_seconds)) + "s"
        else:
            uptime = str(int(uptime)) + " seconds"
        return uptime 
Example 14
Source File: proxylib.py    From arkc-client with GNU General Public License v2.0 5 votes vote down vote up
def get_uptime():
    if os.name == 'nt':
        import ctypes
        try:
            tick = ctypes.windll.kernel32.GetTickCount64()
        except AttributeError:
            tick = ctypes.windll.kernel32.GetTickCount()
        return tick / 1000.0
    elif os.path.isfile('/proc/uptime'):
        with open('/proc/uptime', 'rb') as fp:
            uptime = fp.readline().strip().split()[0].strip()
            return float(uptime)
    elif any(os.path.isfile(os.path.join(x, 'uptime')) for x in os.environ['PATH'].split(os.pathsep)):
        # http://www.opensource.apple.com/source/lldb/lldb-69/test/pexpect-2.4/examples/uptime.py
        pattern = r'up\s+(.*?),\s+([0-9]+) users?,\s+load averages?: ([0-9]+\.[0-9][0-9]),?\s+([0-9]+\.[0-9][0-9]),?\s+([0-9]+\.[0-9][0-9])'
        output = os.popen('uptime').read()
        duration, _, _, _, _ = re.search(pattern, output).groups()
        days, hours, mins = 0, 0, 0
        if 'day' in duration:
            m = re.search(r'([0-9]+)\s+day', duration)
            days = int(m.group(1))
        if ':' in duration:
            m = re.search(r'([0-9]+):([0-9]+)', duration)
            hours = int(m.group(1))
            mins = int(m.group(2))
        if 'min' in duration:
            m = re.search(r'([0-9]+)\s+min', duration)
            mins = int(m.group(1))
        return days * 86400 + hours * 3600 + mins * 60
    else:
        #TODO: support other platforms
        return None 
Example 15
Source File: Notify.py    From securedrop-workstation with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_uptime_seconds():
    # Obtain current uptime
    with open("/proc/uptime", "r") as f:
        uptime_seconds = float(f.readline().split()[0])
    return uptime_seconds 
Example 16
Source File: uptime.py    From sal with Apache License 2.0 5 votes vote down vote up
def get_uptime():
    cmd = ['/usr/sbin/sysctl', '-n', 'kern.boottime']
    p = subprocess.Popen(
        cmd, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
        text=True)
    (output, unused_error) = p.communicate()
    sec = int(re.sub(r'.*sec = (\d+),.*', '\\1', output))
    up = int(time.time() - sec)
    return up if up > 0 else -1 
Example 17
Source File: driver.py    From nova-powervm with Apache License 2.0 5 votes vote down vote up
def get_host_uptime(self):
        """Returns the result of calling "uptime" on the target host."""
        # trivial implementation from libvirt/driver.py for consistency
        out, err = n_utils.execute('env', 'LANG=C', 'uptime')
        return out 
Example 18
Source File: linux_proc.py    From darkc0de-old-stuff with GNU General Public License v3.0 5 votes vote down vote up
def getUptime():
    """
    Get system uptime: return datetime.timedelta object.
    """
    uptime = readProc('uptime')
    uptime = uptime.strip().split()
    uptime = float(uptime[0])
    return timedelta(seconds=uptime) 
Example 19
Source File: openwrt_router.py    From boardfarm with BSD 3-Clause Clear License 5 votes vote down vote up
def get_seconds_uptime(self):
        '''Return seconds since last reboot. Stored in /proc/uptime'''
        self.sendline('\ncat /proc/uptime')
        self.expect('(\d+).(\d+) (\d+).(\d+)\r\n')
        seconds_up = int(self.match.group(1))
        self.expect(self.prompt)
        return seconds_up 
Example 20
Source File: openstack.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_uptime_for_single_hypervisor(self, hyp_id):
        url = '{0}/os-hypervisors/{1}/uptime'.format(self.get_nova_endpoint(), hyp_id)
        headers = {'X-Auth-Token': self.get_auth_token()}

        resp = self._make_request_with_auth_fallback(url, headers)
        uptime = resp['hypervisor']['uptime']
        return self._parse_uptime_string(uptime) 
Example 21
Source File: stats.py    From core with GNU General Public License v3.0 5 votes vote down vote up
def get_uptime():
    """Get system uptime."""
    n = datetime.datetime.now() - datetime.datetime.fromtimestamp(psutil.boot_time())
    m, s = divmod(n.seconds, 60)
    h, m = divmod(m, 60)
    d, h = divmod(h, 24)

    return [s, m, h, n.days] 
Example 22
Source File: __init__.py    From agent with MIT License 5 votes vote down vote up
def get_uptime():
    """
    Returns the uptime in seconds.
    """

    with open('/proc/uptime', 'r') as f:
        uptime_seconds = float(f.readline().split()[0])

    return uptime_seconds 
Example 23
Source File: osx.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def get_uptime():
  """Returns uptime in seconds since system startup.

  Includes sleep time.
  """
  CTL_KERN = 1
  KERN_BOOTTIME = 21
  result = _timeval()
  _sysctl(CTL_KERN, KERN_BOOTTIME, result)
  start = float(result.tv_sec) + float(result.tv_usec) / 1000000.
  return time.time() - start 
Example 24
Source File: adb_commands_safe.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def GetUptime(self):
    """Returns the device's uptime in second."""
    # This is an high level functionality but is needed by self.Reboot().
    out, _ = self.Shell('cat /proc/uptime')
    if out:
      return float(out.split()[0])
    return None 
Example 25
Source File: sysstats.py    From landscape-client with GNU General Public License v2.0 5 votes vote down vote up
def get_uptime(uptime_file=u"/proc/uptime"):
    """
    This parses a file in /proc/uptime format and returns a floating point
    version of the first value (the actual uptime).
    """
    with open(uptime_file, 'r') as ufile:
        data = ufile.readline()
    up, idle = data.split()
    return float(up) 
Example 26
Source File: snippets.py    From python-docs-samples with Apache License 2.0 5 votes vote down vote up
def get_uptime_check_config(config_name):
    client = monitoring_v3.UptimeCheckServiceClient()
    config = client.get_uptime_check_config(config_name)
    pprint.pprint(config)
# [END monitoring_uptime_check_get]


# [START monitoring_uptime_check_delete] 
Example 27
Source File: services.py    From CTF_AWD_Platform with MIT License 5 votes vote down vote up
def get_uptime():
    """
    Get uptime
    """
    try:
        with open('/proc/uptime', 'r') as f:
            uptime_seconds = float(f.readline().split()[0])
            uptime_time = str(timedelta(seconds=uptime_seconds))
            data = uptime_time.split('.', 1)[0]

    except Exception as err:
        data = str(err)

    return data 
Example 28
Source File: status.py    From paasta with Apache License 2.0 5 votes vote down vote up
def get_pod_uptime(pod_deployed_timestamp: str):
    pod_creation_time = datetime.strptime(pod_deployed_timestamp, "%Y-%m-%dT%H:%M:%SZ")
    pod_uptime = datetime.utcnow() - pod_creation_time
    pod_uptime_total_seconds = pod_uptime.total_seconds()
    pod_uptime_days = divmod(pod_uptime_total_seconds, 86400)
    pod_uptime_hours = divmod(pod_uptime_days[1], 3600)
    pod_uptime_minutes = divmod(pod_uptime_hours[1], 60)
    pod_uptime_seconds = divmod(pod_uptime_minutes[1], 1)
    return f"{int(pod_uptime_days[0])}d{int(pod_uptime_hours[0])}h{int(pod_uptime_minutes[0])}m{int(pod_uptime_seconds[0])}s" 
Example 29
Source File: frontend.py    From ga4gh-server with Apache License 2.0 5 votes vote down vote up
def getPreciseUptime(self):
        """
        Returns the server precisely.
        """
        return self.startupTime.strftime("%H:%M:%S %d %b %Y") 
Example 30
Source File: frontend.py    From ga4gh-server with Apache License 2.0 5 votes vote down vote up
def getNaturalUptime(self):
        """
        Returns the uptime in a human-readable format.
        """
        return humanize.naturaltime(self.startupTime) 
Example 31
Source File: meta.py    From DHV3 with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_bot_uptime(self):
        now = datetime.datetime.utcnow()
        delta = now - self.bot.uptime
        hours, remainder = divmod(int(delta.total_seconds()), 3600)
        minutes, seconds = divmod(remainder, 60)
        days, hours = divmod(hours, 24)
        if days:
            fmt = '{d} days, {h} hours, {m} minutes, and {s} seconds'
        else:
            fmt = '{h} hours, {m} minutes, and {s} seconds'

        return fmt.format(d=days, h=hours, m=minutes, s=seconds) 
Example 32
Source File: general.py    From modmail with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_bot_uptime(self, *, brief=False):
        hours, remainder = divmod(int(self.bot.uptime.total_seconds()), 3600)
        minutes, seconds = divmod(remainder, 60)
        days, hours = divmod(hours, 24)
        if not brief:
            if days:
                fmt = "{d} days, {h} hours, {m} minutes, and {s} seconds"
            else:
                fmt = "{h} hours, {m} minutes, and {s} seconds"
        else:
            fmt = "{h}h {m}m {s}s"
            if days:
                fmt = "{d}d " + fmt
        return fmt.format(d=days, h=hours, m=minutes, s=seconds) 
Example 33
Source File: rpiMonitor.py    From BerePi with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_uptime():
    p = os.popen("uptime")
    return p.read()

## function get_ifconfig : return network interfaces info 
Example 34
Source File: stackdrivermonitoring.py    From ScoutSuite with GNU General Public License v2.0 5 votes vote down vote up
def get_uptime_checks(self, project_id: str):
        try:
            client = stackdrivermonitoring.UptimeCheckServiceClient()
            name = client.project_path(project_id)
            return await run_concurrently(lambda: [r for r in client.list_uptime_check_configs(name)])
        except Exception as e:
            print_exception('Failed to retrieve uptime checks: {}'.format(e))
            return [] 
Example 35
Source File: RPGBot.py    From RPGBot with GNU General Public License v3.0 5 votes vote down vote up
def get_bot_uptime(self):
        """Get time between now and when the bot went up"""
        now = datetime.datetime.utcnow()
        delta = now - self.uptime
        hours, remainder = divmod(int(delta.total_seconds()), 3600)
        minutes, seconds = divmod(remainder, 60)
        days, hours = divmod(hours, 24)

        if days:
            fmt = '{d} days, {h} hours, {m} minutes, and {s} seconds'
        else:
            fmt = '{h} hours, {m} minutes, and {s} seconds'

        return fmt.format(d=days, h=hours, m=minutes, s=seconds)