示例#1
0
def status (self): # pylint: disable=unused-argument
  rc = {
    "hostname": socket.gethostname (),
    "cpu": {
      "count": psutil.cpu_count (),
      "times": psutil.cpu_times (),
      "percent": psutil.cpu_percent (percpu = True),
      },
    "memory": {
      "virtual": psutil.virtual_memory (),
      "swap": psutil.swap_memory (),
      },
    "net": psutil.net_io_counters (),
    "uptime": {
      "ut": psutil.boot_time (),
      "since": logtool.time_str (psutil.boot_time (), slug = True),
      },
    "disk": {},
    }
  for part in psutil.disk_partitions ():
    rc["disk"]["mounts"] = {
      part.mountpoint: psutil.disk_usage (part.mountpoint),
    }
  for disk, io in psutil.disk_io_counters (perdisk = True).items ():
    rc["disk"]["io"] = {
      disk: io
    }
  return rc
def get_initial_since_values(since):
    last_snapshot_time = (
        psutil.boot_time() if hasattr(
            psutil, 'boot_time') else psutil.BOOT_TIME)
    if since == 'EPOCH':
        since_timestamp = 0
    elif since == 'BOOT':
        since_timestamp = (
            psutil.boot_time() if hasattr(
                psutil, 'boot_time') else psutil.BOOT_TIME)

    elif since == 'LASTSNAPSHOT':
        # subsequent snapshots will update this value
        since_timestamp = last_snapshot_time
    else:

        # check if the value of since is a UTC timestamp (integer)

        try:
            since_timestamp = int(since)
        except:
            logger.error(
                'Invalid value since={0}, defaulting to BOOT'.format(since))
            # subsequent snapshots will update this value
            since_timestamp = last_snapshot_time
    return since_timestamp, last_snapshot_time
示例#3
0
 def update(self):
     """Get the latest system information."""
     import psutil
     if self.type == 'disk_use_percent':
         self._state = psutil.disk_usage(self.argument).percent
     elif self.type == 'disk_use':
         self._state = round(psutil.disk_usage(self.argument).used /
                             1024**3, 1)
     elif self.type == 'disk_free':
         self._state = round(psutil.disk_usage(self.argument).free /
                             1024**3, 1)
     elif self.type == 'memory_use_percent':
         self._state = psutil.virtual_memory().percent
     elif self.type == 'memory_use':
         self._state = round((psutil.virtual_memory().total -
                              psutil.virtual_memory().available) /
                             1024**2, 1)
     elif self.type == 'memory_free':
         self._state = round(psutil.virtual_memory().available / 1024**2, 1)
     elif self.type == 'swap_use_percent':
         self._state = psutil.swap_memory().percent
     elif self.type == 'swap_use':
         self._state = round(psutil.swap_memory().used / 1024**3, 1)
     elif self.type == 'swap_free':
         self._state = round(psutil.swap_memory().free / 1024**3, 1)
     elif self.type == 'processor_use':
         self._state = round(psutil.cpu_percent(interval=None))
     elif self.type == 'process':
         if any(self.argument in l.name() for l in psutil.process_iter()):
             self._state = STATE_ON
         else:
             self._state = STATE_OFF
     elif self.type == 'network_out' or self.type == 'network_in':
         counters = psutil.net_io_counters(pernic=True)
         if self.argument in counters:
             counter = counters[self.argument][IO_COUNTER[self.type]]
             self._state = round(counter / 1024**2, 1)
         else:
             self._state = STATE_UNKNOWN
     elif self.type == 'packets_out' or self.type == 'packets_in':
         counters = psutil.net_io_counters(pernic=True)
         if self.argument in counters:
             self._state = counters[self.argument][IO_COUNTER[self.type]]
         else:
             self._state = STATE_UNKNOWN
     elif self.type == 'ipv4_address' or self.type == 'ipv6_address':
         addresses = psutil.net_if_addrs()
         if self.argument in addresses:
             self._state = addresses[self.argument][IF_ADDRS[self.type]][1]
         else:
             self._state = STATE_UNKNOWN
     elif self.type == 'last_boot':
         self._state = dt_util.as_local(
             dt_util.utc_from_timestamp(psutil.boot_time())
         ).date().isoformat()
     elif self.type == 'since_last_boot':
         self._state = dt_util.utcnow() - dt_util.utc_from_timestamp(
             psutil.boot_time())
 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)
示例#5
0
 def update(self):
     """ Get the latest system informations. """
     import psutil
     if self.type == 'disk_use_percent':
         self._state = psutil.disk_usage(self.argument).percent
     elif self.type == 'disk_use':
         self._state = round(psutil.disk_usage(self.argument).used /
                             1024**3, 1)
     elif self.type == 'disk_free':
         self._state = round(psutil.disk_usage(self.argument).free /
                             1024**3, 1)
     elif self.type == 'memory_use_percent':
         self._state = psutil.virtual_memory().percent
     elif self.type == 'memory_use':
         self._state = round((psutil.virtual_memory().total -
                              psutil.virtual_memory().available) /
                             1024**2, 1)
     elif self.type == 'memory_free':
         self._state = round(psutil.virtual_memory().available / 1024**2, 1)
     elif self.type == 'swap_use_percent':
         self._state = psutil.swap_memory().percent
     elif self.type == 'swap_use':
         self._state = round(psutil.swap_memory().used / 1024**3, 1)
     elif self.type == 'swap_free':
         self._state = round(psutil.swap_memory().free / 1024**3, 1)
     elif self.type == 'processor_use':
         self._state = round(psutil.cpu_percent(interval=None))
     elif self.type == 'process':
         if any(self.argument in l.name() for l in psutil.process_iter()):
             self._state = STATE_ON
         else:
             self._state = STATE_OFF
     elif self.type == 'network_out':
         self._state = round(psutil.net_io_counters(pernic=True)
                             [self.argument][0] / 1024**2, 1)
     elif self.type == 'network_in':
         self._state = round(psutil.net_io_counters(pernic=True)
                             [self.argument][1] / 1024**2, 1)
     elif self.type == 'packets_out':
         self._state = psutil.net_io_counters(pernic=True)[self.argument][2]
     elif self.type == 'packets_in':
         self._state = psutil.net_io_counters(pernic=True)[self.argument][3]
     elif self.type == 'ipv4_address':
         self._state = psutil.net_if_addrs()[self.argument][0][1]
     elif self.type == 'ipv6_address':
         self._state = psutil.net_if_addrs()[self.argument][1][1]
     elif self.type == 'last_boot':
         self._state = dt_util.datetime_to_date_str(
             dt_util.as_local(
                 dt_util.utc_from_timestamp(psutil.boot_time())))
     elif self.type == 'since_last_boot':
         self._state = dt_util.utcnow() - dt_util.utc_from_timestamp(
             psutil.boot_time())
示例#6
0
    def _use_time_info(self):
        self._use_time["count_user"] = len(psutil.users())
	now = datetime.datetime.now()
	boot_time = datetime.datetime.fromtimestamp(psutil.boot_time())
	live_time = now - boot_time 
	self._use_time["live_time"] = str(live_time.days) + '天' + \
			 str(live_time.seconds//3600) + '小时' + str((live_time.seconds//60)%60) + '秒'
        self._use_time["start_time"] = str(
            datetime.datetime.fromtimestamp(
                psutil.boot_time()).strftime(
                    "%Y-%m-%d %H:%M:%S"))
        return self._use_time
示例#7
0
文件: __init__.py 项目: auduny/chains
 def _get_sysinfo(self):
     """ Gather system info into a dictionary for sendEvent.
         This is information that rarely if ever changes. Well, yeah, this changed with the uptime stats.
     """
     sysinfo = {
         'hostname': os.uname()[1],
         'cpus': ps.cpu_count(logical=False),
         'cpu_cores': ps.cpu_count(),
         'architecture': pf.architecture()[0],
         'bin_format': pf.architecture()[1],
         'up_since': datetime.datetime.fromtimestamp(ps.boot_time()).strftime("%Y-%m-%d %H:%M:%S"),
         'uptime': int((datetime.datetime.now() - datetime.datetime.fromtimestamp(ps.boot_time())).total_seconds() / 60),
     }
     return sysinfo
示例#8
0
文件: web.py 项目: sunhughees/psdash
def index():
    load_avg = os.getloadavg()
    uptime = datetime.now() - datetime.fromtimestamp(psutil.boot_time())
    disks = get_disks()
    users = get_users()

    netifs = build_network_interfaces()
    netifs.sort(key=lambda x: x.get('bytes_sent'), reverse=True)

    data = {
        'os': platform.platform().decode('utf-8'),
        'hostname': socket.gethostname().decode('utf-8'),
        'uptime': str(uptime).split('.')[0],
        'load_avg': load_avg,
        'cpus': psutil.cpu_count(),
        'vmem': psutil.virtual_memory(),
        'swap': psutil.swap_memory(),
        'disks': disks,
        'cpu_percent': psutil.cpu_times_percent(0),
        'users': users,
        'net_interfaces': netifs,
        'page': 'overview',
        'is_xhr': request.is_xhr
    }

    return render_template('index.html', **data)
示例#9
0
文件: writer.py 项目: simsong/dfxml
    def add_DFXML_execution_environment(self,e):
        ee = ET.SubElement(e, 'execution_environment')
        uname = os.uname()
        uname_fields = ['os_sysname','host','os_release','os_version','arch']
        for i in range(len(uname_fields)):
            ET.SubElement(ee, uname_fields[i]).text = uname[i]

        ET.SubElement(ee, 'command_line').text = " ".join([sys.executable] + sys.argv)
        ET.SubElement(ee, 'uid').text = str(os.getuid())
        ET.SubElement(ee, 'username').text = pwd.getpwuid(os.getuid())[0]
        ET.SubElement(ee, 'cwd').text = os.getcwd()
        ET.SubElement(ee, 'start_time').text = datetime.datetime.now().isoformat()
        try:
            import psutil
            ET.SubElement(ee, 'boot_time').text = datetime.datetime.fromtimestamp(psutil.boot_time()).isoformat()
        except ImportError:
            pass
        env = ET.SubElement(ee, 'vars')
        count = 0

        # output the environment. Unfortunately, quoteattr doesn'doesn't quote enough, so we need to have it quote
        # every possible invalid value that might be in the environment
        entities = {}
        for ch in range(0,32):
            entities[chr(ch)] = "\\%03o" % ch
        for ch in range(127,256):
            entities[chr(ch)] = "\\%03o" % ch


        from xml.sax.saxutils import quoteattr,escape
        for (name,value) in os.environ.items():
            ET.SubElement(env, 'var', {'name':escape(name,entities), 'value':escape(value,entities)})
示例#10
0
	def do_GET(self):
             self.send_response(200)
             self.end_headers()
             res = ""
             boot_time = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
             cpu_util = psutil.cpu_percent(interval=1, percpu=True)
             mem = psutil.virtual_memory()
             res="<table width='40%' border=2><tr bgcolor='#CEF6F5'><td>BOOT TIME</td><td>" + boot_time + "</td></tr>"
             res += "<tr><td>CPU UTILIZATION</td><td><table border=0 width='100%'>"
             i = 1
             for cpu in cpu_util:
                 res += "<tr><td>CPU {}</td><td bgcolor=".format(i)
                 if (cpu < 50) :
                     res += "'#008000'> {}%</td></tr>".format(cpu)
                 else:
                     res += "'#ff0000'> {}%</td></tr>".format(cpu)
                 i = i+1
             res += "</table></td></tr><tr bgcolor='#CEF6F5'><td>AVAILABLE MEMORY</td><td>" + str(mem.available) + "</td></tr>"
             res += "<tr><td>USED MEMORY</td><td>" + str(mem.used) + "</td></tr>"
             res += "<tr ><td bgcolor='#CEF6F5'>USED PERCENTAGE</td><td bgcolor="
             if ( mem.percent < 50) :
                 res += "'#008000'>" + str(mem.percent) + "</td></tr></table></div>"
             else:
                 res += "'#ff0000'>" + str(mem.percent) + "</td></tr></table></div>"
             self.wfile.write(bytes(res, 'utf-8'))
             return
示例#11
0
def on_message(client, userdata, msg):
    command=json.loads(msg.payload.decode('ascii')) #Convert to ascii then json
    print("Received message : "+command+" on topic : "+str(msg.topic))
    
    #Check command and respond accordingly
    if command == 'ifconfig':
      bashCommand = "ifconfig"
      process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
      output = process.communicate()[0]
      message = "{\"Message\":\""+str(output)+"\"}"
      client.publish(topic_result, message)
      print("Sent ls")
    elif command == 'ls':
      bashCommand = "ls"
      process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
      output = process.communicate()[0]
      message = "{\"Message\":\""+str(output)+"\"}"
      client.publish(topic_result, message)
      print("Sent cd")
    elif command == 'bootTime':
      date = datetime.fromtimestamp(psutil.boot_time()).strftime('%Y-%m-%d %H:%M')
      message = json.dumps({"Message":"Booted at "+date})
      client.publish(topic_result, message)
    elif command == 'exit':
        sys.exit(1)
    else:
      message = "{\"Message\":\"I received an unknown command\"}"
      client.publish(topic_result, message)
      print("Sent unknown")
示例#12
0
文件: p9-1.py 项目: zhewuqw/Python
def my_app(environ, start_response):
    status = '200 OK'
    headers = [('Content-type', 'html; charset=utf-8')]
    start_response(status, headers)
    boot_time = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
    cpu_util = psutil.cpu_percent(interval=1, percpu=True)

    message = "<h1>My System information</h1>"
    message += "<table>"
    message += "<tr><th bgcolor = 'lightblue' > BOOT TIME </th><th bgcolor='lightgreen' >" \
               + str(boot_time) + "</th></tr>"
    message += "<tr><th bgcolor = 'lightblue' > CPU UTILIZATION </th></tr>"
    i = 1
    for cpu in cpu_util:
        message += "<tr><th bgcolor = 'lightblue' > CPU " + str(i) + "</th><th bgcolor='lightpink'>" \
                   + str(cpu) + "</th><tr>"
        i += 1
    mem = psutil.virtual_memory()
    THRESHOLD = 100 * 1024 * 1024  # 100MB
    message += "<tr><th bgcolor = 'lightblue' > AVAILABLE MEMORY </th><th bgcolor='lightgreen'>" \
               + str(mem.available) + "</th></tr>"
    message += "<tr><th bgcolor = 'lightblue' > USED MEMORY </th><th bgcolor = 'lightgreen' >" \
               + str(mem.used) + "</th></tr>"
    message += "<tr><th bgcolor = 'lightblue' > USED PERCENTAGE </th><th bgcolor= 'lightgreen' >" \
               + str(mem.percent) + "</th></tr>"
    message += "</table>"
    return [bytes(message, 'utf-8')]
示例#13
0
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=ctapipe_resources.__version__,
        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(),
        ),
        arguments=sys.argv,
        start_time_utc=Time.now().isot,
    )
示例#14
0
def sysinfo():
    boot_start = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(psutil.boot_time()))
    time.sleep(0.5)
    cpu_usage = psutil.cpu_percent()
    ram = int(psutil.virtual_memory().total / (1027 * 1024))
    ram_percent = psutil.virtual_memory().percent
    swap = int(psutil.swap_memory().total / (1027 * 1024))
    swap_percent = psutil.swap_memory().percent
    net_sent = psutil.net_io_counters().bytes_sent
    net_recv = psutil.net_io_counters().bytes_recv
    net_spkg = psutil.net_io_counters().packets_sent
    net_rpkg = psutil.net_io_counters().packets_recv
    sysinfo_string = ""
    if __name__ == "__main__":
        bfh = r'%'
        print(" \033[1;32m开机时间:%s\033[1;m" % boot_start)
        print(" \033[1;32m当前CPU使用率:%s%s\033[1;m" % (cpu_usage, bfh))
        print(" \033[1;32m物理内存:%dM\t使用率:%s%s\033[1;m" % (ram, ram_percent, bfh))
        print(" \033[1;32mSwap内存:%dM\t使用率:%s%s\033[1;m" % (swap, swap_percent, bfh))
        print(" \033[1;32m发送:%d Byte\t发送包数:%d个\033[1;m" % (net_sent, net_spkg))
        print(" \033[1;32m接收:%d Byte\t接收包数:%d个\033[1;m" % (net_recv, net_rpkg))
        for i in psutil.disk_partitions():
            print(" \033[1;32m盘符: %s 挂载点: %s 使用率: %s%s\033[1;m" % (i[0], i[1], psutil.disk_usage(i[1])[3], bfh))

        sysinfo_string = '开机时间: ' + boot_start + '\n'
        sysinfo_string += '当前CPU使用率: ' + str(cpu_usage) + '%\n'
        sysinfo_string += '物理内存: ' + str(ram) + 'M\t使用率: ' + str(ram_percent) + '%\t'
        sysinfo_string += 'Swap内存: ' + str(swap) + 'M\t使用率: ' + str(swap_percent) + '%\n'
        return sysinfo_string

    else:
        file = open("sysinfo.log", "a")
        file.write("CPU:%s   \tRAM:%s\tnet_recv:%d\tNet_sent:%d\r\n" % (cpu_usage, ram_percent, net_recv, net_sent))
        file.flush()
        file.close()
def run_info():
    return dict(
        cpu_usage = psutil.cpu_percent(),
        boot_time = psutil.boot_time(),
        swap_usage = psutil.swap_memory().used,
        mem_usage = psutil.virtual_memory().used
    )
示例#16
0
    def _boot_time_linux():
        try:
            return psutil.boot_time()
        except:
            pass

        # Old psutil versions
        try:
            return psutil.BOOT_TIME
        except:
            pass

        # Get info from proc
        try:
            f = open('/proc/stat', 'r')
            for line in f:
                if line.startswith('btime'):
                    f.close()
                    return float(line.strip().split()[1])
            f.close()
            return 0
        except:
            pass

        raise Exception("Cannot get uptime")
示例#17
0
    def _health_loop(self):
        topic='{0}/linux_state'.format(self.id)
        
        msg=linux_state()
        msg.header=header()
        msg.header.seq=0
        
        while True:
            msg.header.seq+=1
            msg.header.time=time.time()
            
            msg.temp=get_temp()
            
            cpu_perc=[0,0,0,0]
            cpu_percent=psutil.cpu_percent(percpu=True)
            for i in range(len(cpu_percent)):
                cpu_perc[i] = cpu_percent[i]
                
                
            msg.cpu_use=cpu_perc
            msg.load_average=os.getloadavg()
            
            msg.uptime=time.time()-psutil.boot_time()
            msg.memory_use=psutil.virtual_memory().used/(1024*1024)

            try:
                self.lcm.publish(topic, msg.encode())
            except IOError, e:
                print e
            time.sleep(.5)
def my_app(environ, start_response):
    status = '200 OK'
    headers = [('Content-type', 'html; charset=utf-8')]
    start_response(status, headers)
    boot_time = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
    cpu_utilization = psutil.cpu_percent(interval=1, percpu=True)

    message = "<h1>My System information</h1>"
    message += "<table>"
    message += "<tr><th bgcolor = 'lightblue' > Boot time </th><th bgcolor='lightgreen' >" \
               + str(boot_time) + "</th></tr>"
    message += "<tr><th bgcolor = 'lightblue' > CPU Utilization </th></tr>"
    i = 1
    for cpu in cpu_utilization:
        message += "<tr><th bgcolor = 'lightblue' > CPU " + str(i) + "</th><th bgcolor='lightpink'>" \
                   + str(cpu) + "</th><tr>"
        i += 1
    mem = psutil.virtual_memory()
    Threshold = 100 * 1024 * 1024  # 100MB
    message += "<tr><th bgcolor = 'lightblue' > Available memory </th><th bgcolor='lightgreen'>" \
               + str(mem.available) + "</th></tr>"
    message += "<tr><th bgcolor = 'lightblue' > Used memory </th><th bgcolor = 'lightgreen' >" \
               + str(mem.used) + "</th></tr>"
    message += "<tr><th bgcolor = 'lightblue' > Used percentage </th><th bgcolor= 'lightgreen' >" \
               + str(mem.percent) + "</th></tr>"
    message += "</table>"
    return [bytes(message, 'utf-8')]
示例#19
0
文件: panel.py 项目: cedricde/mmc
 def serialize(self):
     memory = psutil.virtual_memory()
     if hasattr(psutil, 'boot_time'):
     	uptime = str(datetime.now() - datetime.fromtimestamp(psutil.boot_time()))
     else:
     	uptime = str(datetime.now() - datetime.fromtimestamp(psutil.BOOT_TIME))
     	        
     try:
         dist = platform.linux_distribution()
     except:
         dist = platform.dist()
     return {
         'hostname': socket.gethostname(),
         'dist': dist,
         'load': [str(val) for val in os.getloadavg()],
         'uptime': uptime,
         'users': len(getUsersLdap()),
         'memory': {
             'total': size_format(memory.total),
             'used': size_format(memory.used),
             'available': size_format(memory.available),
             'free': size_format(memory.free),
             'percent': memory.percent
         }
     }
示例#20
0
文件: admin.py 项目: Bala96/grr
  def Run(self, arg):
    """Returns the client stats."""
    if arg is None:
      arg = rdf_client.GetClientStatsRequest()

    proc = psutil.Process(os.getpid())
    meminfo = proc.memory_info()
    response = rdf_client.ClientStats(
        RSS_size=meminfo.rss,
        VMS_size=meminfo.vms,
        memory_percent=proc.memory_percent(),
        bytes_received=stats.STATS.GetMetricValue("grr_client_received_bytes"),
        bytes_sent=stats.STATS.GetMetricValue("grr_client_sent_bytes"),
        create_time=long(proc.create_time() * 1e6),
        boot_time=long(psutil.boot_time() * 1e6))

    samples = self.grr_worker.stats_collector.cpu_samples
    for (timestamp, user, system, percent) in samples:
      if arg.start_time < timestamp < arg.end_time:
        sample = rdf_client.CpuSample(timestamp=timestamp,
                                      user_cpu_time=user,
                                      system_cpu_time=system,
                                      cpu_percent=percent)
        response.cpu_samples.Append(sample)

    samples = self.grr_worker.stats_collector.io_samples
    for (timestamp, read_bytes, write_bytes) in samples:
      if arg.start_time < timestamp < arg.end_time:
        sample = rdf_client.IOSample(timestamp=timestamp,
                                     read_bytes=read_bytes,
                                     write_bytes=write_bytes)
        response.io_samples.Append(sample)

    self.Send(response)
示例#21
0
 def uptime(self):
     # now = time.localtime() 
     now = time.time() 
     # print(now)
     uptime = now - psutil.boot_time() 
     # print(uptime)
     return int(uptime / 86400)
def getUptime():
    uptime_file = "/proc/uptime"
    if os.path.exists(uptime_file):
        with open(uptime_file, 'r') as f:
            return f.read().split(' ')[0].strip("\n")
    else:
        return time.time() - psutil.boot_time()
示例#23
0
    def collect(self):
        meta = super(SystemMetaCollector, self).collect()
        meta.update({
            'boot': int(psutil.boot_time()) * 1000,
            'hostname': self.hostname,
            'uname': None,
            'network': {
                'interfaces': [],
                'default': None
            },
            'ec2': None,
        })

        for method in (
            self.uname,
            self.network,
            self.ec2
        ):
            try:
                method(meta)
            except Exception as e:
                exception_name = e.__class__.__name__
                context.log.error('failed to collect meta %s due to %s' % (method.__name__, exception_name))
                context.log.debug('additional info:', exc_info=True)

        self.object.metad.meta(meta)
示例#24
0
def get_properties(group):
    mem = psutil.virtual_memory()
    disk = psutil.disk_usage('/')
    properties = {}
    if group is None or group == 'fresh':
        if platform.machine().startswith('arm') and platform.system() == 'Linux':  # raspberry pi
            properties["cpuTemp"] = get_rpi_cpu_temperature()
        properties["ramAvailable"] = int(mem.available / (1024 * 1024))
        properties["usedDiskSpaceRoot"] = int(disk.used / (1024 * 1024))
        properties["bootTime"] = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime(Publisher.DATE_FORMAT)
        properties["cpuLoad"] = psutil.cpu_percent(interval=3)

    if group is None or group == 'seldom':
        if platform.system() == 'Darwin':  # mac
            properties["release"] = platform.mac_ver()[0]
        elif platform.machine().startswith('arm') and platform.system() == 'Linux':  # raspberry pi
            properties["distribution"] = "{} {}".format(platform.dist()[0], platform.dist()[1])
        for i in NET_INTERFACES:
            properties["{}IpAddress".format(i)] = get_ip(i)
        properties["totalDiskSpaceRoot"] = int(disk.total / (1024 * 1024))
        properties["hostname"] = platform.node()
        properties["machine"] = platform.machine()
        properties["system"] = platform.system()
        properties["cpuProcessorCount"] = psutil.cpu_count()
        properties["ramTotal"] = int(mem.total / (1024 * 1024))

    return properties
示例#25
0
文件: ps.py 项目: DavideyLee/salt
def boot_time(time_format=None):
    '''
    Return the boot time in number of seconds since the epoch began.

    CLI Example:

    time_format
        Optionally specify a `strftime`_ format string. Use
        ``time_format='%c'`` to get a nicely-formatted locale specific date and
        time (i.e. ``Fri May  2 19:08:32 2014``).

        .. _strftime: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

        .. versionadded:: 2014.1.4

    .. code-block:: bash

        salt '*' ps.boot_time
    '''
    try:
        b_time = int(psutil.boot_time())
    except AttributeError:
        # get_boot_time() has been removed in newer psutil versions, and has
        # been replaced by boot_time() which provides the same information.
        b_time = int(psutil.get_boot_time())
    if time_format:
        # Load epoch timestamp as a datetime.datetime object
        b_time = datetime.datetime.fromtimestamp(b_time)
        try:
            return b_time.strftime(time_format)
        except TypeError as exc:
            raise SaltInvocationError('Invalid format string: {0}'.format(exc))
    return b_time
示例#26
0
def server_health_app(environ, start_response):
  boot_time = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
  cpu_util = psutil.cpu_percent(interval=1, percpu=True)
  mem = psutil.virtual_memory()
  message = ""
  status = '200 OK'
  headers = [('Content-type', 'html; charset=utf-8')]
  start_response(status, headers)
  message += "<h1>Server Health</h1>"
  message += "<table border =\"1\" allign=\"center\">"
  message += "<tr>"#row 1
  message += "<td><b>BOOT TIME:</td>"
  message += "<td>{}".format(boot_time)+"</td>"
  message += "</tr>"
  message += "<tr>"#row 2
  message += "<td><b>CPU UTILIZATION:</td>"
  message += "<td>"
  i=1
  for cpu in cpu_util:
    if cpu > 10:
      message += "<font color = \"red\">"
    else:
      message += "<font color = \"black\">"
    message += "CPU {} : {}%<br>".format(i, cpu)
    i+=1
  message += "</td>"	
  message += "<tr><td><b>AVAILABLIE MEMORY:</td>" #row 3
  message += "<td>{}</tr>".format(mem.available)
  message += "<tr><td><b>USED MEMORY:</td>"#row 4
  message += "<td>{}</td></tr>".format(mem.used)
  message += "<tr><td><b>USED PERCENTAGE:</td>"#row 5
  message += "<td>{}</td></tr>".format(mem.percent)
 
  return[bytes(message,'utf-8')]
示例#27
0
def Sysinfo():  
    Hostname = platform.node()
    Sys_version = platform.platform()
    Boot_Start = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(psutil.boot_time()))    
    time.sleep(0.5)  
    Cpu_usage = psutil.cpu_percent()  
    RAM = int(psutil.virtual_memory().total/(1027*1024))  
    RAM_percent = psutil.virtual_memory().percent  
    Swap = int(psutil.swap_memory().total/(1027*1024))  
    Swap_percent = psutil.swap_memory().percent  
    Net_sent = psutil.net_io_counters().bytes_sent  
    Net_recv = psutil.net_io_counters().bytes_recv  
    Net_spkg = psutil.net_io_counters().packets_sent  
    Net_rpkg = psutil.net_io_counters().packets_recv  
    BFH = r'%'
    print " \033[1;32m主机名: %s\033[1;m" % Hostname  
    print " \033[1;32m系统版本: %s\033[1;m" % Sys_version  
    print " \033[1;32m开机时间:%s\033[1;m"  % Boot_Start  
    print " \033[1;32m当前CPU使用率:%s%s\033[1;m" % (Cpu_usage,BFH)  
    print " \033[1;32m物理内存:%dM\t使用率:%s%s\033[1;m" % (RAM,RAM_percent,BFH)  
    print " \033[1;32mSwap内存:%dM\t使用率:%s%s\033[1;m" % (Swap,Swap_percent,BFH)  
    print " \033[1;32m发送:%d Byte\t发送包数:%d个\033[1;m" % (Net_sent,Net_spkg)  
    print " \033[1;32m接收:%d Byte\t接收包数:%d个\033[1;m" % (Net_recv,Net_rpkg)  
  
    for i in psutil.disk_partitions():  
        print " \033[1;32m盘符: %s 挂载点: %s 使用率: %s%s\033[1;m" % (i[0],i[1],psutil.disk_usage(i[1])[3],BFH)  
    for key in psutil.net_if_addrs().keys():  
        print " \033[1;32m网卡: %s IP: %s\033[1;m" % (key,psutil.net_if_addrs()[key][0][1])  
示例#28
0
def healthcheck():
    import psutil
    import humanfriendly

    now = time.time()
    pid = os.getgid()
    ppid = os.getppid()

    current_process = psutil.Process(pid=ppid)  # how about launching under gunicorn?
    process_uptime = current_process.create_time()
    process_uptime_delta = now - process_uptime
    process_uptime_human = humanfriendly.format_timespan(process_uptime_delta)

    system_uptime = psutil.boot_time()
    system_uptime_delta = now - system_uptime
    system_uptime_human = humanfriendly.format_timespan(system_uptime_delta)

    free_memory = psutil.disk_usage('/').free
    free_memory_human = humanfriendly.format_size(free_memory)

    return {
        'status': 'Operational',
        'free_disk_space': free_memory_human,
        'system_uptime': system_uptime_human,
        'process_uptime': process_uptime_human,
    }
示例#29
0
文件: admin.py 项目: google/grr
  def Run(self, arg):
    """Returns the client stats."""
    if arg is None:
      arg = rdf_client_action.GetClientStatsRequest()

    proc = psutil.Process(os.getpid())
    meminfo = proc.memory_info()
    boot_time = rdfvalue.RDFDatetime.FromSecondsSinceEpoch(psutil.boot_time())
    create_time = rdfvalue.RDFDatetime.FromSecondsSinceEpoch(proc.create_time())
    stats_collector = stats_collector_instance.Get()
    response = rdf_client_stats.ClientStats(
        RSS_size=meminfo.rss,
        VMS_size=meminfo.vms,
        memory_percent=proc.memory_percent(),
        bytes_received=stats_collector.GetMetricValue(
            "grr_client_received_bytes"),
        bytes_sent=stats_collector.GetMetricValue("grr_client_sent_bytes"),
        create_time=create_time,
        boot_time=boot_time)

    response.cpu_samples = self.grr_worker.stats_collector.CpuSamplesBetween(
        start_time=arg.start_time, end_time=arg.end_time)
    response.io_samples = self.grr_worker.stats_collector.IOSamplesBetween(
        start_time=arg.start_time, end_time=arg.end_time)

    self.Send(response)
    def _add_sys_meta(self):
        try:

            self.element.add_attribute('platform', platform.system())
            self.element.add_attribute('agent', self.version)

            if psutil:
                self.element.add_attribute('cpus', psutil.cpu_count())
                mem = psutil.virtual_memory()
                self.element.add_attribute(
                    'ram', get_human_readable_size(mem.total))
                self.element.add_attribute('ram bytes', mem.total)
                self.element.add_attribute(
                    'boottime', str(datetime.datetime.fromtimestamp(psutil.boot_time())))

            if platform.system().startswith('Linux'):
                if check_lsb() is None:
                    supported_dists = platform._supported_dists + ('system',)
                    dist = platform.linux_distribution(
                        supported_dists=supported_dists)

                else:
                    dist = check_lsb()

                self.element.add_attribute('distribution_name', str(dist[0]))
                self.element.add_attribute(
                    'distribution_version', str(dist[1]))
                if dist[2] != '':
                    self.element.add_attribute('distribution_id', str(dist[2]))

        except Exception as e:
            logging.debug(e)
            pass
示例#31
0
 def get_bootime_timestamp():
     """Retourne le Timestamp du bootime"""
     return psutil.boot_time()
示例#32
0
def risk():
	risk_score = 0

	# Check uptime
	uptime_sec    = time.time() - psutil.boot_time()
	uptime_minute = uptime_sec * 60
	uptime_hour   = uptime_minute * 60

	# Tally risk score
	if uptime_hour < 1:
		risk_score += 5

	# Clock
	ran_int = random.randint(1,21)*5
	time.sleep(ran_int)

	# Disk Size
	# with os.statvfs, we need to multiply block sizes by block counts to get bytes
	stats = os.statvfs(path)
	total = stats.f_frsize * stats.f_blocks
	free  = stats.f_frsize * stats.f_bavail

	total_mb   = total * 100 # Calculates from bytes to Mb
	total_free = free * 100

	disk_usage ={ "total": total,
		      "free" : free,
		      "used" : total - free, }

	# Tally risk score
	if total_free < 40:
		risk_score += 5

	# Clock
	ran_int = random.randint(1,21)*5
	time.sleep(ran_int)


    # Anti VM
	VMProcessList = ["vmsrvc.exe", "vmware.exe","vbox.exe",
		"vmvss.exe","vmscsi.exe","vmhgfs.exe","vboxservice.exe",
		"vmxnet.exe","vmx_svga.exe","vmmemctl.exe",
		"autoruns.exe","autorunsc.exe","vmusbmouse.exe","vmtools.exe",
		"regmon.exe","vboxtray.exe", "vmrawdsk.exe","joeboxcontrol.exe",
		"joeboxserver.exe","vmtoolsd.exe","vmwaretray.exe","vmwareuser.exe",
		"vmusrvc.exe","xenservice.exe"]

    # Debug proc check
	DebugList = ["ollydbg.exe","ProcessHacker.exe", "fiddler.exe",
		"tcpview.exe","df5serv.exe", "filemon.exe","procmon.exe","regmon.exe",
		"procexp.exe","idaq.exe","idaq64.exe","ImmunityDebugger.exe","Wireshark.exe",
		"dumpcap.exe","HookExplorer.exe","ImportREC.exe","PETools.exe","LordPE.exe",
		"SysInspector.exe","proc_analyzer.exe","sysAnalyzer.exe","sniff_hit.exe","windbg.exe",
		"prl_cc.exe","prl_tools.exe","xenservice.exe"]

	DBG_out = []

	for proc in psutil.process_iter():
		if proc.name() in DebugList:
			#print(proc)
			DBG = True

			try:
				p = psutil.Process(proc.pid)
				time.sleep(0.33)
				p.kill()
			except Exception as e:
				#print e
				DBG_out.append(proc)
				continue

		elif proc.name() in VMProcessList:
			#print(proc)
			VM = True

			continue

	"""
	If there were DBG procs check to see
	if we managed to kill them all by counting
	the number of items in the DBG_out array

	In case it's empty assume we killed all
	and switch DBG back to False
	"""
	cnt = 0
	for i in DBG_out:
		cnt += 1

	if not cnt < 1:
		DBG = False

	if DBG and VM == True:
		risk_score += 15
		return risk_score

	elif DBG == True:
		risk_score += 12
		return risk_score

	elif VM == True:
		risk_score += 11
		return risk_score

	else:
		return risk_score
示例#33
0
 def test_boot_time(self):
     # Duplicate of test_system.py. Keep it anyway.
     self.assertIsInstance(psutil.boot_time(), float)
示例#34
0
 def get_bootime_delay():
     """Retourne le delai du bootime"""
     return time.time() - psutil.boot_time()
############################
#get disk partitions
print("Disk partitions:", psutil.disk_partitions())

#get disk uage
print("Disk Usage:", psutil.disk_usage('/'))

#get disk IO
print("Disk Usage:", psutil.disk_io_counters(perdisk=False))

##############################
#   OTHERS
#############################
#get users
print("Users:", psutil.users())

#Get boot time
print("Boot time:", psutil.boot_time())

#Get Pids
print("Pids:", psutil.pids())
p = psutil.Process(7152)
print("Process details for pid:", p)
print("Exe:", p.exe())
print("CWD:", p.cwd())
print("cmdline:", p.cmdline())
print("Parent Process:", p.parent())
print("Parent Process id:", p.ppid())
print("creation time of the  Process:", p.create_time())
# there are other features like suspend, terminate ,resume of processes and querying process's memory utilization
示例#36
0
println(psutil.cpu_times())
println(psutil.cpu_times().user)

mem = psutil.virtual_memory()
println(mem)
println(mem.total)

partitions = psutil.disk_partitions()
println(partitions)
println(partitions[1])
println(psutil.disk_usage('/'))


println(psutil.net_io_counters())
println(psutil.net_io_counters(pernic=True))


println(psutil.users())
println(psutil.boot_time())

ps = psutil.pids()
println(ps)
p = psutil.Process(1)
println(p.name())
println(p.exe())
println(p.status())
println(p.memory_percent())

#https://pypi.python.org/pypi/psutil

示例#37
0
def get_boot_time():
    boot_time_timestamp = psutil.boot_time()
    bt = datetime.fromtimestamp(boot_time_timestamp)
    last_boot = (
        f"{bt.month}/{bt.day}/{bt.year} {bt.hour}:{bt.minute}:{bt.second}")
    return last_boot
示例#38
0
def get_uptime():
	return int(time.time() - psutil.boot_time())
示例#39
0
 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)
示例#40
0
 def test_boot_time(self):
     s = sysctl('sysctl kern.boottime')
     s = s[s.find(" sec = ") + 7:]
     s = s[:s.find(',')]
     btime = int(s)
     self.assertEqual(btime, psutil.boot_time())
示例#41
0
    def create_suite_execution(self, suite_execution, verbose=True, *args, **kwargs):
        # type: (dict, bool, list, dict) -> bool
        """
        Uploads log file to logbook site
        """
        se = {}
        try:
            se = suite_execution.copy()
            suite = kwargs.get('suite', None)  # type: Suite
            try:
                se['hostname'] = get_hostname()
                se['host_uptime'] = int(psutil.boot_time())
                mem = psutil.virtual_memory()
                se['host_memory_total'] = int(mem.total/1024/1042)
                se['host_memory_free'] = int(mem.free/1024/1042)

            except:
                pass
            try:
                se['host_cpu_usage'] = get_cpu_load_avg()
                se['host_system'] = platform.system()
                se['host_release'] = platform.release()
                se['host_version'] = platform.version()
                se['host_python_version'] = platform.python_version()
                se['host_user'] = os.getlogin()
                se['host_cpu_count'] = os.cpu_count()
            except:
                pass

            try:
                se['product_version'] = suite_execution['prod_v']
                del se['prod_v']
            except:
                pass
            try:
                project_list_ready = []
                project = os.environ.get('GERRIT_PROJECT', '')  # type: str
                if project.strip():
                    se['GERRIT_PROJECT'] = project.strip()
            except:
                pass
            try:
                clusters_list_ready = []
                clusters = os.environ.get('CLUSTER', '')  # type: str
                if clusters:
                    clusters_list = clusters.split(',')  # type: list
                    if clusters_list:
                        for x in clusters_list:
                            if x.strip() not in clusters_list_ready:
                                clusters_list_ready.append(x.strip())
                se['clusters'] = clusters_list_ready
            except:
                pass
            try:
                se['description'] = suite_execution['desc']
                del se['desc']
            except:
                pass
            try:
                se['components'] = suite_execution['_components']
                del se['_components']
            except:
                pass

            gb = os.environ.get('GERRIT_BRANCH')  # type: str
            mr = os.environ.get('MANIFEST_REVISION')  # type: str
            if gb and len(gb) > 3:
                se['GERRIT_BRANCH'] = gb
            elif mr and len(mr) > 3:
                se['GERRIT_BRANCH'] = mr
            on_jenkins = False
            if os.environ.get('BUILD_ID', '') != '':
                on_jenkins = True
            se['is_jenkins'] = on_jenkins
            if on_jenkins:
                try:
                    gpsn = os.environ.get('GERRIT_PATCHSET_NUMBER', '')  # type: str
                    gcn = os.environ.get('GERRIT_CHANGE_NUMBER', '')  # type: str
                    gci = os.environ.get('GERRIT_CHANGE_ID', '')  # type: str
                    if gcn != '' and int(gcn) > 0 and gci != '' and gpsn != '' and gb != '':
                        se['PRE_COMMIT'] = f'{gb}_{gci}_{gcn}_{gpsn}'  # TODO gpsn - not used?
                except:
                    pass

            headers = {'Content-Type': 'application/json'}
            lbk_api = LogbookAPI()
            try:
                self.progress += 1
                r = lbk_api.urlopen_lbk(
                    # url=self.suite_execution_url,
                    url='upload/create_suite_execution',
                    method='POST',
                    data=se,
                    headers=headers,
                    verbose=False,
                    sleep_on_error=0,
                    timeout=SUITE_CREATE_TIMEOUT
                )
                filters = []
                if 'FILTERS' in r:
                    filters = r['FILTERS']
                    if suite:
                        suite.set_filters(filters)
                if 'SUITE_EXECUTION_ID' in r:

                    sid = r['SUITE_EXECUTION_ID']
                    if suite:
                        self._suite_execution_id = suite.set_suite_execution_id(sid)
                    logging.warning(f'LogBook Suite Execution http://{LOGBOOK_DOMAIN}/suites/show/{sid} '
                                    f'for {se["summary"]}. Filters {len(filters)}')
            except (socket.timeout, Exception) as ex:
                if hasattr(ex, 'args') and len(ex.args) and 'Name or service not known' in ex.args[0]:
                    return True
                logging.error(f'[create_suite_execution]: {ex}')
            finally:
                self.progress -= 1
            return True
        except Exception as ex:
            if verbose:
                logging.error(f'Failed is suiteExecution creation {ex}')
                logging.exception(ex)
                logging.debug(f'{se}')
        return False
示例#42
0
 def get_bootime_formatted():
     """Retourne la date formatté du bootime """
     return datetime.datetime.fromtimestamp(
         psutil.boot_time()).strftime("%a %d %b %Y (S%W) %H:%M:%S")
示例#43
0
    hm1.MouseRightDown = onMouse_rightdown

    hm1.MouseRightUp = onMouse_rightup

    hm1.HookMouse()

    # 进入循环,如不手动关闭,程序将一直处于监听状态


if __name__ == "__main__":

    # 打开日志文件

    # 电脑开机时间作为文件名
    from datetime import datetime
    dt = datetime.fromtimestamp(psutil.boot_time())
    windowsstarttime = dt.strftime("%Y-%m-%d-%H-%M-%S")
    print windowsstarttime
    fobj = open("D:\pycharm\pydata\mouse-" + windowsstarttime + ".txt", "a")
    # fobj.write("时间    位置    操作     进程名hash值   进程名  \n")

    # 以日期为文件名

    # fobj = open("D:\pycharm\pydata\mouse-"+datetime.now().date().strftime('%Y%m%d') + '.txt', 'a')

    # 新线程执行的代码:
    print('thread %s is running..感受一下被支配的恐惧!!   哈哈哈哈.....' %
          threading.current_thread().name)

    # 创建hook句柄
    hm = pyHook.HookManager()
示例#44
0
def get_uptime():
	'''Get current system uptime'''
	print(str(timedelta(seconds=round(time.time()-psutil.boot_time(),0)))[:-3])
示例#45
0
import psutil
import platform
from datetime import datetime

print("-" * 40, "Sys Info", "-" * 40)
uname = platform.uname()
print(f"System: {uname.system}")
print(f"Node Name: {uname.node}")
print(f"Release: {uname.release}")
print(f"Version: {uname.version}")
print(f"Machine: {uname.machine}")
print(f"Processor: {uname.processor}")

print("-" * 40, "Boot Time", "-" * 40)
boot_time_timestamp = psutil.boot_time()
bt = datetime.fromtimestamp(boot_time_timestamp)
print(
    f"Boot Time: {bt.day}.{bt.month}.{bt.year} {bt.hour}:{bt.minute}:{bt.second}"
)

print("-" * 40, "CPU Info", "-" * 40)
print("Actual Cores:", psutil.cpu_count(logical=False))
print("Logical Cores:", psutil.cpu_count(logical=True))
print(f"Max Frequency: {psutil.cpu_freq().max:.1f}Mhz")
print(f"Current Frequency: {psutil.cpu_freq().current:.1f}Mhz")
print(f"CPU Usage: {psutil.cpu_percent()}%")
print("CPU Usage/Core:")
for i, perc in enumerate(psutil.cpu_percent(percpu=True, interval=1)):
    print(f"Core {i}: {perc}%")

示例#46
0
def get_last_boot():
    return str(as_local(utc_from_timestamp(psutil.boot_time())).isoformat())
示例#47
0
 def get_my_booting_time():
     return datetime.datetime.fromtimestamp(psutil.boot_time())
示例#48
0
              ('boot_time', ''),
              ('users', 'name')
              ]

log_data_lists = []
for function in log_values:
    if function[0] == 'Datetime':
        log_data_lists.append(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    elif function[0] == 'disk_usage':
        function_value = "ps." + function[0] + "('/')." + function[1]
        log_data_lists.append(eval(function_value))
    elif function[0] == 'users':
        function_value = "ps." + function[0] + "()[0]." + function[1]
        log_data_lists.append(eval(function_value))
    elif function[0] == 'boot_time':
        log_data_lists.append(str(-(datetime.datetime.fromtimestamp(ps.boot_time()) - datetime.datetime.now())))
    elif function[0] == 'Process':
        function_value = "len(ps." + function[0] + "()." + function[1] + "())"
        log_data_lists.append(eval(function_value))
    elif function[0] == 'getloadavg':
        function_value = "os." + function[0] + "()"
        for value in range(len(eval(function_value))):
            log_data_lists.append(eval(function_value)[value])
    elif len(function[1]):
        function_value = "ps." + function[0] + "()." + function[1]
        log_data_lists.append(eval(function_value))
    else:
        function_value = "ps." + function[0] + "()"
        log_data_lists.append(eval(function_value))
log_file_key_value = ['DateTime',
                      'Cpu Count',
示例#49
0
 def boot_time():
     # psutil-2.x.x is not backward compatible to psutil-1.x.x
     try:
         return psutil.boot_time()
     except AttributeError:
         return psutil.get_boot_time()
示例#50
0
 def boot_time():
     return psutil.boot_time()
 def test_boot_time(self):
     bt = psutil.boot_time()
     self.assertIsInstance(bt, float)
     self.assertGreater(bt, 0)
     self.assertLess(bt, time.time())
示例#52
0
    def _get_status(self):
        def meminfo():
            return '{:.1f}%'.format(psutil.virtual_memory().percent)

        def temperature():
            if 'temperature_method' in self.config:
                vars = {'temp': 'err'}
                try:
                    exec(self.config['temperature_method'], globals(), vars)
                except Exception as ex:
                    vars['temp'] = 'err: ' + str(ex)
                return vars['temp']
            elif os.path.exists('/sys/class/thermal/thermal_zone0/temp'):
                with open('/sys/class/thermal/thermal_zone0/temp',
                          'r') as tmpo:
                    temp = int(tmpo.read())
                return '{:.1f}d'.format(temp / 1000)
            else:
                return ''

        def docker_status(container):
            s = subprocess.check_output([DOCKER_EXEC,
                                         'ps']).decode('utf-8').split()
            return container in s

        status = {}

        status['shortcuts'] = cfg.get('shortcuts', [])

        status['services'] = {}
        if self.services:
            for _ in self.services:
                if '@' not in _['name']:
                    status['services'][_['name']] = {
                        'status': False,
                        'dispname': _.get('dispname', _['name']),
                        'name': _['name'],
                        'actions': _.get('actions', [])
                    }
                elif 'container' in _:
                    status['services'][_['name']] = {
                        'status': docker_status(_['container']),
                        'dispname': _.get('dispname', _['container']),
                        'name': _['name'],
                        'actions': _.get('actions', [])
                    }

            for _ in psutil.process_iter():
                short_key = _.name() + ':'
                if os.name == 'nt': long_key = short_key
                else: long_key = short_key + _.username()
                s = None
                if short_key in self.serv_procs:
                    s = self.serv_procs[short_key]
                if long_key in self.serv_procs:
                    s = self.serv_procs[long_key]
                if s is None:
                    continue
                if s.get('uname') and s['uname'] != _.username():
                    continue
                if s.get('args') and s['args'] not in _.cmdline():
                    continue

                status['services'][s['name']]['status'] = True

        if self.nodes:
            status['nodes'] = {}
            for m, n in self.nodes.items():
                status['nodes'][m] = {
                    'type': type(n).__name__,
                    'dispname': n.dispname,
                    'name': m
                }

        t = time.time() - psutil.boot_time()
        status[
            'uptime'] = '{}:{:02d}:{:02d}:{:02d} {:.01f}% {} Mem: {}'.format(
                int(t / 86400),
                int(t / 3600) % 24, int(t % 3600 / 60), int(t % 60),
                psutil.cpu_percent(interval=None),
                ' '.join(['%.2f' % _ for _ in os.getloadavg()]), meminfo())

        status['disks'] = []
        for disk in psutil.disk_partitions():
            try:
                usage = psutil.disk_usage(disk.mountpoint)
                status['disks'].append('{} {:.01f}%'.format(
                    disk.mountpoint, usage.percent))
            except PermissionError:
                pass

        status['temp'] = temperature()
        return status
示例#53
0
文件: sys.py 项目: websfx/DCMP
 def uptime(self):
     Uptime = datetime.datetime.fromtimestamp(psutil.boot_time())
     Nowtime = datetime.datetime.now()
     return int(round((Nowtime - Uptime).seconds / 3600))
示例#54
0
#cpu逻辑个数
cpunum = psutil.cpu_count()
#cpu物理个数
cpuPhysical = psutil.cpu_count(logical=False)
print(cpu)

#内存信息
mem = psutil.virtual_memory()
print(mem)
mem.total
mem.free
mem.percent

#磁盘信息
disk = psutil.disk_partitions()  #磁盘完整信息
psutil.disk_usage('/')  #分区信息
psutil.disk_io_counters()
psutil.disk_io_counters(perdisk=True)  #单个分区io个数
print(disk)

#网络信息
net = psutil.net_io_counters(pernic=True)
print(net)

#当前用户
user = psutil.users()
print(user)
#开机时间
boottime = psutil.boot_time()
print(boottime)
示例#55
0
 def test_get_uptime(self):
     sysinfo = self.service.get_sysinfo()
     uptime = int(time.time() - psutil.boot_time())
     self.assertEqual(sysinfo['uptime'], uptime)
示例#56
0
def system_start_time():
    import datetime
    time = datetime.datetime.fromtimestamp(psutil.boot_time())
    print(time)
示例#57
0
def StatusPage():


    f = open("/proc/device-tree/model")
    piType = f.read()
    boottime =datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S") 
    
    Row1 = html.Div(
        [
                    dbc.Button(
                        ["Raspberry Pi", dbc.Badge(piType, color="light", className="ml-1")],
                        color="primary",),
                    dbc.Button(
                        ["SW2 Start Time ", dbc.Badge(boottime, color="light", className="ml-1")],
                        color="primary",),
                    dbc.Button(
                        ["Pi Boot Time ", dbc.Badge(boottime, color="light", className="ml-1")],
                        color="primary",),
        ])

    Row2 = dbc.Row(
                [
                    daq.Gauge(
                        id = {'type' : 'SPGdynamic', 'GaugeType' :'pi-loading'},
                        label="Pi CPU Loading",
                        value=0,
                        color={"gradient":True,"ranges":{"green":[0,50],"yellow":[50,85],"red":[85,100]}},
                        showCurrentValue=True,
                        units="%",
                        size=190,
                        max = 100,
                        min = 0,
                    ),
                    daq.Gauge(
                        id = {'type' : 'SPGdynamic', 'GaugeType' :'pi-memory'},
                        label="Pi Memory Usage",
                        value=0,
                        color={"gradient":True,"ranges":{"green":[0,50],"yellow":[50,85],"red":[85,100]}},
                        max=100,
                        size=190,
                        showCurrentValue=True,
                        units="%",

                    ),

                    daq.Gauge(
                        id = {'type' : 'SPGdynamic', 'GaugeType' :'pi-disk'},
                        label="Pi Disk Free",
                        value=0,
                        showCurrentValue=True,
                        units="%",
                        size=190,
                        color={"gradient":True,"ranges":{"red":[0,30],"yellow":[30,65],"green":[65,100]}},
                        max = 100,
                        min = 0,
                        ),

                    daq.Gauge(
                        id = {'type' : 'SPGdynamic', 'GaugeType' :'pi-temp'},
                        label="Pi CPU Temperature(C)",
                        value=0,
                        color={"gradient":True,"ranges":{"green":[0,50],"yellow":[50,85],"red":[85,130]}},
                        showCurrentValue=True,
                        units="C",
                        size=190,
                        max = 130,
                        min = 0,
                    ),


                ],
		no_gutters=True,

		)

    Row3 = html.Div(


         )

    Row4 = html.Div(
            [
    html.Div(id='log')
            ]
            )

    Row5 = html.Div(
                [
                    dbc.Alert("No Alarm", color="primary"),
        ],
		   style={'margin-top' : "-90px"}

    )
    OutdoorIndicator = returnOutdoorIndicator()
    IndoorIndicators = returnIndoorIndicators()
    PiThrottled = returnPiThrottled()
  
    Row8 = html.Div(
        PiThrottled,
        )

    Row6 = html.Div(
        OutdoorIndicator, 
    )
    Row7 = html.Div(
        IndoorIndicators,
    )
    #layout = dbc.Container([
    layout = dbc.Container([
        Row1, Row2, Row5, Row3,html.Br(), Row8,html.Br(), Row4,html.Br(), Row6, html.Br(),Row7],
        className="status-1",
    )
    return layout
示例#58
0
 def uptime(self, opts=None):
     """Get system uptime miliseconds"""
     return (time.time() - psutil.boot_time()) * 1000
示例#59
0
 def update(self):
     """Get the latest system information."""
     import psutil
     if self.type == 'disk_use_percent':
         self._state = psutil.disk_usage(self.argument).percent
     elif self.type == 'disk_use':
         self._state = round(
             psutil.disk_usage(self.argument).used / 1024**3, 1)
     elif self.type == 'disk_free':
         self._state = round(
             psutil.disk_usage(self.argument).free / 1024**3, 1)
     elif self.type == 'memory_use_percent':
         self._state = psutil.virtual_memory().percent
     elif self.type == 'memory_use':
         virtual_memory = psutil.virtual_memory()
         self._state = round(
             (virtual_memory.total - virtual_memory.available) / 1024**2, 1)
     elif self.type == 'memory_free':
         self._state = round(psutil.virtual_memory().available / 1024**2, 1)
     elif self.type == 'swap_use_percent':
         self._state = psutil.swap_memory().percent
     elif self.type == 'swap_use':
         self._state = round(psutil.swap_memory().used / 1024**2, 1)
     elif self.type == 'swap_free':
         self._state = round(psutil.swap_memory().free / 1024**2, 1)
     elif self.type == 'processor_use':
         self._state = round(psutil.cpu_percent(interval=None))
     elif self.type == 'process':
         for proc in psutil.process_iter():
             try:
                 if self.argument == proc.name():
                     self._state = STATE_ON
                     return
             except psutil.NoSuchProcess as err:
                 _LOGGER.warning(
                     "Failed to load process with id: %s, old name: %s",
                     err.pid, err.name)
         self._state = STATE_OFF
     elif self.type == 'network_out' or self.type == 'network_in':
         counters = psutil.net_io_counters(pernic=True)
         if self.argument in counters:
             counter = counters[self.argument][IO_COUNTER[self.type]]
             self._state = round(counter / 1024**2, 1)
         else:
             self._state = None
     elif self.type == 'packets_out' or self.type == 'packets_in':
         counters = psutil.net_io_counters(pernic=True)
         if self.argument in counters:
             self._state = counters[self.argument][IO_COUNTER[self.type]]
         else:
             self._state = None
     elif self.type == 'throughput_network_out' or\
             self.type == 'throughput_network_in':
         counters = psutil.net_io_counters(pernic=True)
         if self.argument in counters:
             counter = counters[self.argument][IO_COUNTER[self.type]]
             now = datetime.now()
             if self._last_value and self._last_value < counter:
                 self._state = round(
                     (counter - self._last_value) / 1000**2 /
                     (now - self._last_update_time).seconds, 3)
             else:
                 self._state = None
             self._last_update_time = now
             self._last_value = counter
         else:
             self._state = None
     elif self.type == 'ipv4_address' or self.type == 'ipv6_address':
         addresses = psutil.net_if_addrs()
         if self.argument in addresses:
             for addr in addresses[self.argument]:
                 if addr.family == IF_ADDRS_FAMILY[self.type]:
                     self._state = addr.address
         else:
             self._state = None
     elif self.type == 'last_boot':
         self._state = dt_util.as_local(
             dt_util.utc_from_timestamp(psutil.boot_time())).isoformat()
     elif self.type == 'load_1m':
         self._state = os.getloadavg()[0]
     elif self.type == 'load_5m':
         self._state = os.getloadavg()[1]
     elif self.type == 'load_15m':
         self._state = os.getloadavg()[2]
示例#60
0
def com_system_boot_time():
    """
    Get boot time
    """
    return psutil.boot_time()