Python psutil.boot_time() Examples

The following are 30 code examples of psutil.boot_time(). 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 also want to check out all available functions/classes of the module psutil , or try the search function .
Example #1
Source File: system_status.py    From Paradrop with Apache License 2.0 12 votes vote down vote up
def getSystemInfo(cls):
        system = {
            'boot_time': psutil.boot_time(),
            'cpu_count': psutil.cpu_count(),
            'cpu_stats': psutil.cpu_stats().__dict__,
            'cpu_times': [k.__dict__ for k in psutil.cpu_times(percpu=True)],
            'disk_io_counters': psutil.disk_io_counters().__dict__,
            'disk_usage': [],
            'net_io_counters': psutil.net_io_counters().__dict__,
            'swap_memory': psutil.swap_memory().__dict__,
            'virtual_memory': psutil.virtual_memory().__dict__
        }

        partitions = psutil.disk_partitions()
        for p in partitions:
            if p.mountpoint in cls.INCLUDED_PARTITIONS:
                usage = psutil.disk_usage(p.mountpoint)
                system['disk_usage'].append({
                    'mountpoint': p.mountpoint,
                    'total': usage.total,
                    'used': usage.used
                })

        return system 
Example #2
Source File: computer.py    From pyspectator with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self):
        self.datetime_format = '%H:%M:%S %d/%m/%Y'
        self.__raw_boot_time = psutil.boot_time()
        self.__boot_time = datetime.fromtimestamp(self.raw_boot_time)
        self.__boot_time = self.__boot_time.strftime(self.datetime_format)
        self.__hostname = platform.node()
        self.__os = Computer.__get_os_name()
        self.__architecture = platform.machine()
        self.__python_version = '{} ver. {}'.format(
            platform.python_implementation(), platform.python_version()
        )
        self.__processor = Cpu(monitoring_latency=1)
        self.__nonvolatile_memory = NonvolatileMemory.instances_connected_devices(monitoring_latency=10)
        self.__nonvolatile_memory_devices = set(
            [dev_info.device for dev_info in self.__nonvolatile_memory]
        )
        self.__virtual_memory = VirtualMemory(monitoring_latency=1)
        self.__swap_memory = SwapMemory(monitoring_latency=1)
        self.__network_interface = NetworkInterface(monitoring_latency=3)
        super().__init__(monitoring_latency=3) 
Example #3
Source File: status.py    From hapi with GNU General Public License v3.0 6 votes vote down vote up
def update(self):
        """Function to update the entire class information."""
        self.cpu["percentage"] = psutil.cpu_percent(interval=0.7)
        self.boot = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime(
            "%Y-%m-%d %H:%M:%S")
        virtual_memory = psutil.virtual_memory()
        self.memory["used"] = int(virtual_memory.used/1024)
        self.memory["free"] = int(virtual_memory.free/1024)
        self.memory["cached"] = int(virtual_memory.cached/1024)
        net_io_counters = psutil.net_io_counters()
        self.network["packet_sent"] = net_io_counters.packets_sent
        self.network["packet_recv"] = net_io_counters.packets_recv
        disk_usage = psutil.disk_usage('/')
        self.disk["total"] = int(disk_usage.total/1024)
        self.disk["used"] = int(disk_usage.used/1024)
        self.disk["free"] = int(disk_usage.free/1024)
        self.timestamp = time.time() 
Example #4
Source File: host.py    From django-heartbeat with MIT License 6 votes vote down vote up
def check(request):
    return {
            'hostname': socket.gethostname(),
            'ips': ips,
            'cpus': psutil.cpu_count(),
            'uptime': timesince(datetime.fromtimestamp(psutil.boot_time())),
            'memory': {
                'total': filesizeformat(psutil.virtual_memory().total),
                'available': filesizeformat(psutil.virtual_memory().available),
                'used': filesizeformat(psutil.virtual_memory().used),
                'free': filesizeformat(psutil.virtual_memory().free),
                'percent': psutil.virtual_memory().percent
            },
            'swap': {
                'total': filesizeformat(psutil.swap_memory().total),
                'used': filesizeformat(psutil.swap_memory().used),
                'free': filesizeformat(psutil.swap_memory().free),
                'percent': psutil.swap_memory().percent
            }
        } 
Example #5
Source File: agent.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def run(self, flow_obj=None):
        if not self.is_active():
            return []

        if not self._config.client.writeback.client_id:
            self.enroll()

        message = client.StartupMessage.from_keywords(
            client_id=self._config.client.writeback.client_id,
            boot_time=psutil.boot_time(),
            agent_start_time=START_TIME,
            timestamp=time.time(),
            labels=self._config.client.labels,
            system_info=UnameImpl.from_current_system(session=self._session),
        )
        self._session.logging.debug("Sending client startup message to server.")
        self.location.write_file(message.to_json()) 
Example #6
Source File: test_linux.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def test_procfs_path(self):
        tdir = tempfile.mkdtemp()
        try:
            psutil.PROCFS_PATH = tdir
            self.assertRaises(IOError, psutil.virtual_memory)
            self.assertRaises(IOError, psutil.cpu_times)
            self.assertRaises(IOError, psutil.cpu_times, percpu=True)
            self.assertRaises(IOError, psutil.boot_time)
            # self.assertRaises(IOError, psutil.pids)
            self.assertRaises(IOError, psutil.net_connections)
            self.assertRaises(IOError, psutil.net_io_counters)
            self.assertRaises(IOError, psutil.net_if_stats)
            self.assertRaises(IOError, psutil.disk_io_counters)
            self.assertRaises(IOError, psutil.disk_partitions)
            self.assertRaises(psutil.NoSuchProcess, psutil.Process)
        finally:
            psutil.PROCFS_PATH = "/proc"
            os.rmdir(tdir) 
Example #7
Source File: test_linux.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_procfs_path(self):
        tdir = tempfile.mkdtemp()
        try:
            psutil.PROCFS_PATH = tdir
            self.assertRaises(IOError, psutil.virtual_memory)
            self.assertRaises(IOError, psutil.cpu_times)
            self.assertRaises(IOError, psutil.cpu_times, percpu=True)
            self.assertRaises(IOError, psutil.boot_time)
            # self.assertRaises(IOError, psutil.pids)
            self.assertRaises(IOError, psutil.net_connections)
            self.assertRaises(IOError, psutil.net_io_counters)
            self.assertRaises(IOError, psutil.net_if_stats)
            self.assertRaises(IOError, psutil.disk_io_counters)
            self.assertRaises(IOError, psutil.disk_partitions)
            self.assertRaises(psutil.NoSuchProcess, psutil.Process)
        finally:
            psutil.PROCFS_PATH = "/proc"
            os.rmdir(tdir) 
Example #8
Source File: system_module.py    From stephanie-va with MIT License 6 votes vote down vote up
def tell_system_status(self):
        import psutil
        import platform
        import datetime

        os, name, version, _, _, _ = platform.uname()
        version = version.split('-')[0]
        cores = psutil.cpu_count()
        cpu_percent = psutil.cpu_percent()
        memory_percent = psutil.virtual_memory()[2]
        disk_percent = psutil.disk_usage('/')[3]
        boot_time = datetime.datetime.fromtimestamp(psutil.boot_time())
        running_since = boot_time.strftime("%A %d. %B %Y")
        response = "I am currently running on %s version %s.  " % (os, version)
        response += "This system is named %s and has %s CPU cores.  " % (name, cores)
        response += "Current disk_percent is %s percent.  " % disk_percent
        response += "Current CPU utilization is %s percent.  " % cpu_percent
        response += "Current memory utilization is %s percent. " % memory_percent
        response += "it's running since %s." % running_since
        return response 
Example #9
Source File: test_linux.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_procfs_path(self):
        tdir = self.get_testfn()
        os.mkdir(tdir)
        try:
            psutil.PROCFS_PATH = tdir
            self.assertRaises(IOError, psutil.virtual_memory)
            self.assertRaises(IOError, psutil.cpu_times)
            self.assertRaises(IOError, psutil.cpu_times, percpu=True)
            self.assertRaises(IOError, psutil.boot_time)
            # self.assertRaises(IOError, psutil.pids)
            self.assertRaises(IOError, psutil.net_connections)
            self.assertRaises(IOError, psutil.net_io_counters)
            self.assertRaises(IOError, psutil.net_if_stats)
            # self.assertRaises(IOError, psutil.disk_io_counters)
            self.assertRaises(IOError, psutil.disk_partitions)
            self.assertRaises(psutil.NoSuchProcess, psutil.Process)
        finally:
            psutil.PROCFS_PATH = "/proc" 
Example #10
Source File: reporter.py    From ray with Apache License 2.0 6 votes vote down vote up
def get_all_stats(self):
        now = to_posix_time(datetime.datetime.utcnow())
        network_stats = self.get_network_stats()

        self.network_stats_hist.append((now, network_stats))
        self.network_stats_hist = self.network_stats_hist[-7:]
        then, prev_network_stats = self.network_stats_hist[0]
        netstats = ((network_stats[0] - prev_network_stats[0]) / (now - then),
                    (network_stats[1] - prev_network_stats[1]) / (now - then))

        return {
            "now": now,
            "hostname": self.hostname,
            "ip": self.ip,
            "cpu": self.get_cpu_percent(),
            "cpus": self.cpu_counts,
            "mem": self.get_mem_usage(),
            "workers": self.get_workers(),
            "boot_time": self.get_boot_time(),
            "load_avg": self.get_load_avg(),
            "disk": self.get_disk_usage(),
            "gpus": self.get_gpu_usage(),
            "net": netstats,
        } 
Example #11
Source File: system_sensor.py    From ptop with MIT License 5 votes vote down vote up
def update(self):
        # updating values
        self.currentValue['text']['user'] = getpass.getuser()
        self.currentValue['text']['host_name'] = socket.gethostname()
        self.currentValue['text']['running_time'] = datetime.timedelta(seconds=int(time.time() - psutil.boot_time())) 
Example #12
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 #13
Source File: tasks.py    From bitnodes-hardware with MIT License 5 votes vote down vote up
def system_info_task():
    """
    Enumerates and caches processor, memory and storage information.
    """
    processor = None
    system = platform.system()
    if system == 'Linux':
        with open('/proc/cpuinfo') as cpuinfo:
            for line in cpuinfo:
                line = line.strip()
                if ':' in line:
                    key, value = line.split(':', 1)
                    key = key.strip()
                    if key in ('model name', 'Processor'):
                        processor = value.strip()
    elif system == 'Darwin':
        processor = subprocess.check_output(
            ['/usr/sbin/sysctl', '-n', 'machdep.cpu.brand_string']).strip()
    else:
        processor = platform.processor()

    # Physical devices only
    partitions = {}
    for partition in disk_partitions():
        partitions[partition.mountpoint] = disk_usage(partition.mountpoint)

    boot_datetime = datetime.utcfromtimestamp(boot_time()).replace(tzinfo=pytz.UTC)

    system_info = {
        'boot_datetime': boot_datetime,
        'processor': processor,
        'memory': virtual_memory().total,
        'storage': partitions,
    }
    logger.debug('system_info: %s', system_info)
    cache.set('system_info', system_info, 3600) 
Example #14
Source File: test_linux.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def test_boot_time_mocked(self):
        with mock.patch('psutil._pslinux.open', create=True) as m:
            self.assertRaises(
                RuntimeError,
                psutil._pslinux.boot_time)
            assert m.called 
Example #15
Source File: test_linux.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def test_boot_time(self):
        vmstat_value = vmstat('boot time')
        psutil_value = psutil.boot_time()
        self.assertEqual(int(vmstat_value), int(psutil_value)) 
Example #16
Source File: test_bsd.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def test_boot_time(self):
        s = sysctl('kern.boottime')
        sys_bt = datetime.datetime.strptime(s, "%a %b %d %H:%M:%S %Y")
        psutil_bt = datetime.datetime.fromtimestamp(psutil.boot_time())
        self.assertEqual(sys_bt, psutil_bt)


# =====================================================================
# --- NetBSD
# ===================================================================== 
Example #17
Source File: test_windows.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def test_boot_time_fluctuation(self):
        # https://github.com/giampaolo/psutil/issues/1007
        with mock.patch('psutil._pswindows.cext.boot_time', return_value=5):
            self.assertEqual(psutil.boot_time(), 5)
        with mock.patch('psutil._pswindows.cext.boot_time', return_value=4):
            self.assertEqual(psutil.boot_time(), 5)
        with mock.patch('psutil._pswindows.cext.boot_time', return_value=6):
            self.assertEqual(psutil.boot_time(), 5)
        with mock.patch('psutil._pswindows.cext.boot_time', return_value=333):
            self.assertEqual(psutil.boot_time(), 333)


# ===================================================================
# sensors_battery()
# =================================================================== 
Example #18
Source File: test_memory_leaks.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def test_boot_time(self):
        self.execute(psutil.boot_time)

    # XXX - on Windows this produces a false positive 
Example #19
Source File: node.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def get_sysinfo(self):
        uptime = int(time.time() - psutil.boot_time())
        sysinfo = {
            'uptime': uptime,
            'hostname': socket.gethostname(),
            'os': platform.platform(),
            'load_avg': os.getloadavg(),
            'num_cpus': psutil.cpu_count()
        }

        return sysinfo 
Example #20
Source File: overview_win.py    From marsnake with GNU General Public License v3.0 5 votes vote down vote up
def get_system_info(response):
    system_info = response["system_info"]

    system_info.append({Klanguage().to_ts(1024) : "{}/{}".format(get_windows_product_info(), platform.machine())})
    system_info.append({Klanguage().to_ts(1025) : common.get_distribution()})
    system_info.append({Klanguage().to_ts(1027) : time_op.timestamp2string(psutil.boot_time())})
    system_info.append({Klanguage().to_ts(1028) : time_op.timestamp2string(time.time())}) 
Example #21
Source File: test_windows.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def test_boot_time(self):
        wmi_os = wmi.WMI().Win32_OperatingSystem()
        wmi_btime_str = wmi_os[0].LastBootUpTime.split('.')[0]
        wmi_btime_dt = datetime.datetime.strptime(
            wmi_btime_str, "%Y%m%d%H%M%S")
        psutil_dt = datetime.datetime.fromtimestamp(psutil.boot_time())
        diff = abs((wmi_btime_dt - psutil_dt).total_seconds())
        # Wmic time is 2-3 secs lower for some reason; that's OK.
        self.assertLessEqual(diff, 3) 
Example #22
Source File: sysinfo.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def up_since():
    """Returns time of last reboot."""
    return psutil.boot_time()


# pylint: disable=C0103 
Example #23
Source File: system_status.py    From Melissa-Core with MIT License 5 votes vote down vote up
def system_uptime(text):
    boot_time = datetime.datetime.fromtimestamp(psutil.boot_time())
    running_since = boot_time.strftime("%A %d. %B %Y")
    response = 'System has been running since ' + running_since
    tts(response) 
Example #24
Source File: test_node.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def test_get_uptime(self):
        sysinfo = self.service.get_sysinfo()
        uptime = int(time.time() - psutil.boot_time())
        self.assertEqual(sysinfo['uptime'], uptime) 
Example #25
Source File: reporter.py    From ray with Apache License 2.0 5 votes vote down vote up
def get_boot_time():
        return psutil.boot_time() 
Example #26
Source File: status.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def status(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    uptime_set = arrow.utcnow().float_timestamp - cmd.bot.start_time.float_timestamp
    processed = round(cmd.bot.queue.processed / uptime_set, 3)
    os_icon, os_color = get_os_icon()
    general_text = f'Latency: **{int(cmd.bot.latency * 1000)}ms**'
    general_text += f'\nPlatform: **{sys.platform.upper()}**'
    general_text += f'\nStarted: **{arrow.get(psutil.boot_time()).humanize()}**'
    cpu_clock = psutil.cpu_freq()
    cpu_clock = round(cpu_clock.current, 2) if cpu_clock else '???'
    cpu_text = f'Count: **{psutil.cpu_count()} ({psutil.cpu_count(logical=False)})**'
    cpu_text += f'\nUsage: **{psutil.cpu_percent()}%**'
    cpu_text += f'\nClock: **{cpu_clock} MHz**'
    avail_mem = psutil.virtual_memory().available
    total_mem = psutil.virtual_memory().total
    used_mem = humanfriendly.format_size(total_mem - avail_mem, binary=True)
    total_mem = humanfriendly.format_size(total_mem, binary=True)
    sigma_mem = humanfriendly.format_size(psutil.Process(os.getpid()).memory_info().rss, binary=True)
    mem_text = f'Me: **{sigma_mem}**'
    mem_text += f'\nUsed: **{used_mem}**'
    mem_text += f'\nTotal: **{total_mem}**'
    response = discord.Embed(color=os_color)
    response.set_author(name=socket.gethostname(), icon_url=os_icon)
    response.add_field(name='General', value=general_text)
    response.add_field(name='CPU', value=cpu_text)
    response.add_field(name='Memory', value=mem_text)
    if cmd.bot.cfg.dsc.bot:
        shard_latency = get_shard_latency(cmd.bot.latencies, pld.msg.guild.shard_id)
        verbose_description = f'Shard: #{pld.msg.guild.shard_id} | '
        verbose_description += f'Latency: {shard_latency}ms | '
        verbose_description += f'Activity: {processed} ev/s'
        response.description = verbose_description
    await pld.msg.channel.send(embed=response) 
Example #27
Source File: getinfo.py    From AIOPS_PLATFORM with MIT License 5 votes vote down vote up
def job():
    with open('./log.txt', 'a') as fp:
        now = datetime.datetime.now()
        boot_time = psutil.boot_time()
        result = '[{}][{}]\n'.format(now, boot_time)
        fp.write(result) 
Example #28
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def boot_time():
            return psutil.boot_time() 
Example #29
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def boot_time():
            return psutil.boot_time() 
Example #30
Source File: provenance.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_system_provenance():
    """ return JSON string containing provenance for all things that are
    fixed during the runtime"""

    bits, linkage = platform.architecture()

    return dict(
        ctapipe_version=ctapipe.__version__,
        ctapipe_resources_version=get_module_version("ctapipe_resources"),
        eventio_version=get_module_version("eventio"),
        ctapipe_svc_path=os.getenv("CTAPIPE_SVC_PATH"),
        executable=sys.executable,
        platform=dict(
            architecture_bits=bits,
            architecture_linkage=linkage,
            machine=platform.machine(),
            processor=platform.processor(),
            node=platform.node(),
            version=platform.version(),
            system=platform.system(),
            release=platform.release(),
            libcver=platform.libc_ver(),
            num_cpus=psutil.cpu_count(),
            boot_time=Time(psutil.boot_time(), format="unix").isot,
        ),
        python=dict(
            version_string=sys.version,
            version=platform.python_version_tuple(),
            compiler=platform.python_compiler(),
            implementation=platform.python_implementation(),
        ),
        environment=_get_env_vars(),
        arguments=sys.argv,
        start_time_utc=Time.now().isot,
    )