# -*- coding:utf-8 -*-
import subprocess
import psutil
class System(object):
"""
获取系统信息
"""
def __init__(self):
self.sys = {}
def get_time_zone(self):
"""
获取系统时区
"""
time_content = subprocess.Popen(
"timedatectl status | grep Time",
shell=True,
stdout=subprocess.PIPE
)
content, _ = time_content.communicate()
if content:
time_zone = content.strip().split(": ")[-1]
time_zone = time_zone.strip()
else:
time_zone = ""
self.sys['time_zone'] = time_zone
def _cpu(self):
"""
获取系统cpu信息
"""
self.sys["cpu"] = {}
self.sys["cpu"]["cpu_percent"] = psutil.cpu_percent()
cpus = subprocess.Popen(
"top -bn 1 | grep -v 'grep' | grep '%Cpu(s):'",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
if cpus.returncode is None:
cpus = cpus.stdout.read().split()
else:
cpus = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
self.sys["cpu"]["user"] = cpus[1]
self.sys["cpu"]["system"] = cpus[3]
self.sys["cpu"]["idle"] = cpus[7]
self.sys["cpu"]["cpus"] = psutil.cpu_percent(percpu=True)
def _disk(self):
"""
获取磁盘信息
"""
total_disk, used_total = 0, 0
for i in psutil.disk_partitions():
mountpoint = i.mountpoint
if "home" in mountpoint and "docker" in mountpoint:
continue
used = psutil.disk_usage(i.mountpoint).used
used_total += used
mountpoint_list = mountpoint.split("/")
if len(mountpoint_list) == 2:
total_disk += psutil.disk_usage(i.mountpoint).total
disk_remain = total_disk - used_total
self.sys['disk'] = {}
self.sys['disk']['total'] = total_disk
self.sys['disk']['used'] = used_total
self.sys['disk']['remain'] = disk_remain
def _memory(self):
"""
获取内存信息
"""
self.sys["memory"] = {}
self.sys["memory"]["total"] = psutil.virtual_memory().total
self.sys["memory"]["percent"] = psutil.virtual_memory().percent
self.sys["memory"]["used"] = psutil.virtual_memory().used
self.sys["memory"]["free"] = psutil.virtual_memory().free
self.sys["memory"]["cached"] = (
psutil.virtual_memory().buffers + psutil.virtual_memory().cached
)
self.sys["memory"]["swap"] = psutil.swap_memory().used
def _traffic(self):
"""
获取所有网卡的流入和流出流量的总和
"""
counters = psutil.net_io_counters(" ")
self.sys["traffic"] = {"send": 0, "recv": 0}
for counter in counters:
if "veth" in counter or "lo" in counter or "docker" in counter:
continue
self.sys["traffic"]["send"] += counters[counter].bytes_sent
self.sys["traffic"]["recv"] += counters[counter].bytes_recv
if __name__ == "__main__":
system = System()
system.get_time_zone()
system._disk()
system._memory()
system._traffic()
print(system.sys)