From f8f2e9c60fc73990d08075df4b6b728c1b12b07d Mon Sep 17 00:00:00 2001 From: PEN <12828106+new_pen@user.noreply.gitee.com> Date: Thu, 25 Jan 2024 04:17:47 +0000 Subject: [PATCH] =?UTF-8?q?add=20=E5=AE=9E=E7=94=A8=E5=B0=8F=E5=B7=A5?= =?UTF-8?q?=E5=85=B7/system=5Flog.py.=20=E5=8F=AF=E4=BB=A5=E8=AE=B0?= =?UTF-8?q?=E5=BD=95=E5=86=85=E5=AD=98,IP,=E8=BF=9B=E7=A8=8B=E4=BF=A1?= =?UTF-8?q?=E6=81=AF=EF=BC=8C=E6=96=B9=E4=BE=BF=E8=A7=82=E5=AF=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: PEN <12828106+new_pen@user.noreply.gitee.com> --- .../system_log.py" | 97 +++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 "\345\256\236\347\224\250\345\260\217\345\267\245\345\205\267/system_log.py" diff --git "a/\345\256\236\347\224\250\345\260\217\345\267\245\345\205\267/system_log.py" "b/\345\256\236\347\224\250\345\260\217\345\267\245\345\205\267/system_log.py" new file mode 100644 index 0000000..4edbac5 --- /dev/null +++ "b/\345\256\236\347\224\250\345\260\217\345\267\245\345\205\267/system_log.py" @@ -0,0 +1,97 @@ +import psutil +import pickle +import time +import json + +def to(mem2): + ms = ["字节","KB","MB","GB","TB","PB"] + for i in range(len(ms)): + if (mem2//1024==0): + break + mem2 = mem2/1024 + return f"{mem2}{ms[i]}" + +def neicun(): + # 获取内存信息 + mem = psutil.virtual_memory() + yo = { + "物理内存": to(mem.total), + "可用内存": to(mem.available), + "已用内存": to(mem.used), + "空闲内存": to(mem.free), + "内存使用率": mem.percent + } + return yo + +def jc(): + tod = [] + attrs_cn = { + 'pid': '进程ID', + 'name': '进程名称', + 'cpu_percent': 'CPU使用率', + 'memory_info': '内存信息' + } + for process in psutil.process_iter(): + try: + process_info = process.as_dict(attrs=list(attrs_cn.keys())) + process_info_cn = {attrs_cn[k]: v for k, v in process_info.items()} + tod.append(process_info_cn) + except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): + tod.append(None) + return tod + +def IP(): + go = psutil.net_connections() + return go[3:4] + +def cout_dict(s): + keys = list(s.keys()) + for i in keys: + print(f"{i}:{s[i]}") + +def save(path): + d = { + "IP": IP(), + "进程": jc(), + "内存": neicun() + } + with open(path, 'w', encoding='utf-8') as f: + json.dump(d, f, ensure_ascii=False) + +def load(path): + with open(path, 'r', encoding='utf-8') as f: + d = json.load(f) + return d + +def log(path_o, go="", t=180, big=True): + n = time.time() + ost = 1 + while True: + if time.time() - n >= t: + n = time.time() + if big: + data = { + "IP": IP(), + "进程": jc(), + "内存": neicun() + } + formatted_data = json.dumps(data, ensure_ascii=False, indent=4) + filename = f"{path_o}/{go}{ost}.log" + print(filename) + with open(filename, 'w', encoding='utf-8') as f: + f.write(formatted_data) + else: + save(f"{path_o}/{go}{ost}.log") + ost += 1 + +#进程信息 +for i in jc(): cout_dict(i) + +#IP信息 +print(IP()) + +#内存信息 +print(neicun()) + +#记录 +log("./out") \ No newline at end of file -- Gitee