1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
| import platform
import cpuinfo
import openpyxl
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import win32com.client
import datetime
import socket
from tkinter import filedialog
from PIL import Image, ImageTk
import psutil
import GPUtil
now = datetime.datetime.now()
def get_system_info():
uname = platform.uname()
cpu_info = cpuinfo.get_cpu_info()
cpu_freq = psutil.cpu_freq()
disks = psutil.disk_partitions()
mem = psutil.virtual_memory()
power_supply = psutil.sensors_battery()
# Инициализация WMI
wmi_obj = win32com.client.GetObject('winmgmts:')
# Запрос WMI для класса Win32_VideoController (класс, представляющий видеокарты)
gpu_list = wmi_obj.InstancesOf('Win32_VideoController')
# Получение информации о материнской плате
motherboard_info = ""
motherboard_list = wmi_obj.InstancesOf('Win32_BaseBoard')
for motherboard in motherboard_list:
motherboard_info = f"Серийный номер материнской платы: {motherboard.SerialNumber}\n" \
f"Производитель материнской платы: {motherboard.Manufacturer}\n" \
f"Версия материнской платы: {motherboard.Version}\n" \
f"Чипсет материнской платы: {motherboard.Product}\n"
break # Выход из цикла после первой материнской платы
output = f"Система: {uname.system}\n"
output += f"Имя компьютера: {uname.node}\n"
output += f"Поколение системы: {uname.release}\n"
output += f"Версия системы: {uname.version}\n\n"
output += "Информация о процессоре:\n"
output += f"Имя процессора: {cpu_info['brand_raw']}\n"
output += f"Серия процессора: {cpu_info['vendor_id_raw']} {cpu_info['brand_raw']} " \
f"{cpu_info['hz_actual_friendly']}\n"
output += f"Архитектура процессора: {cpu_info['arch']}\n"
output += f"Количество ядер процессора: {psutil.cpu_count(logical=True)}\n"
output += f"Максимальная частота: {cpu_freq.max:.2f} МГц\n"
output += f"Минимальная частота: {cpu_freq.min:.2f} МГц\n"
# Получение информации о загруженности процессора
cpu_percent = psutil.cpu_percent(percpu=True)
for i, percent in enumerate(cpu_percent):
output += f"Загруженность ядра {i}: {percent}%\n"
total_percent = psutil.cpu_percent()
output += f"Общая загруженность процессора: {total_percent}%\n\n"
# Получение информации найденной видеокарте
output += "Информация о видеокарте:\n"
for gpu in gpu_list:
if 'NVIDIA' in gpu.Name:
output += f"Название графического процессора: {gpu.Name}\n"
output += f"Производитель видеокарты: {gpu.AdapterCompatibility}\n"
output += f"Версия драйвера видеокарты: {gpu.DriverVersion}\n"
break
elif 'AMD' in gpu.Name:
output += f"Название графического процессора: {gpu.Name}\n"
output += f"Производитель видеокарты: {gpu.AdapterCompatibility}\n"
output += f"Версия драйвера видеокарты: {gpu.DriverVersion}\n"
break
gpus = GPUtil.getGPUs()
for gpu in gpus:
if 'NVIDIA' in gpu.name:
output += f"Загрузка видеокарты: {gpu.load * 100:.0f}%\n"
output += f"Объем видеопамяти: {gpu.memoryFree:.0f} MB\n"
break
elif 'AMD' in gpu.name:
output += f"Загрузка видеокарты: {gpu.load * 100:.0f}%\n"
output += f"Объем видеопамяти: {gpu.memoryFree:.0f} MB\n"
break
output += "\nИнформация об оперативной памяти:\n"
output += f"Общий объем памяти: {mem.total / (1024 ** 2):.2f} MB\n"
output += f"Доступный объем памяти: {mem.available / (1024 ** 2):.2f} MB\n"
output += f"Использованный объем памяти: {mem.used / (1024 ** 2):.2f} MB\n"
output += f"Процент использования памяти: {mem.percent}%\n\n"
output += f"Информация о материнской плате:\n"
output += motherboard_info
output += f"\nБлок питания: {power_supply.power_plugged}\n\n" # БП (ноут-true/false)
for disk in disks:
try:
output += "Информация о жестком диске:\n"
usage = psutil.disk_usage(disk.mountpoint)
output += f" Диск: {disk.device}\n"
output += f" Точка монтирования: {disk.mountpoint}\n"
output += f" Файловая система: {disk.fstype}\n"
output += f" Общий объем диска: {usage.total / (1024 ** 3):.2f} GB\n"
output += f" Использованный объем диска: {usage.used / (1024 ** 3):.2f} GB\n"
output += f" Доступный объем диска: {usage.free / (1024 ** 3):.2f} GB\n\n"
except Exception as e:
print(e)
return output
def create_gui():
# Создание главного окна
window = tk.Tk()
window.title("Информация о системе")
window.configure(background="azure2")
# Создание стиля для виджетов
style = ttk.Style()
style.configure("TButton",
font=("Arial", 12),
background="red",
padding=8)
# Возможность изменения размера окна
window.resizable(True, True)
# Создание текстового поля для вывода информации
output_text = tk.Text(window, height=30, width=100)
output_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# Функция для обновления текстового поля с информацией
def update_output_text(output):
output_text.delete("1.0", tk.END)
output_text.insert(tk.END, output)
def show_info():
output = get_system_info()
update_output_text(output)
show_info_button = ttk.Button(window, text="Показать информацию", command=show_info, style="TButton")
show_info_button.pack()
# Открываем изображение и преобразуем его в формат, поддерживаемый Tkinter
txt_icon = Image.open("txt_icon.png")
txt_icon = txt_icon.resize((35, 35)) # Опционально: изменение размера изображения
txt_icon_photo = ImageTk.PhotoImage(txt_icon)
# Создаём функцию сохранения в txt
def save_to_txt():
output = get_system_info()
try:
# Открытие диалогового окна выбора директории
directory = filedialog.askdirectory()
if directory:
hostname = socket.gethostname()
timestamp = datetime.datetime.now().strftime("%d.%m.%H.%M")
filename = f"{hostname}_{timestamp}.txt"
with open(f"{directory}/{filename}", "w") as file:
file.write(output)
messagebox.showinfo("Успех", f"Информация сохранена")
except Exception as e:
messagebox.showerror("Ошибка", f"Не удалось сохранить информацию: {e}")
# Создаём кнопку с иконкой текстового файла
save_to_txt_button = tk.Button(window, text="Сохранить в txt", image=txt_icon_photo, compound="left",
command=save_to_txt)
save_to_txt_button.configure(font=("Helvetica", 12), foreground="black", background="snow2")
save_to_txt_button.pack()
# Загрузка изображения
excel_icon = Image.open("excel_icon.png") # Путь к изображению и его имя
excel_icon = excel_icon.resize((35, 35)) # Опционально: изменение размера изображения
excel_icon = ImageTk.PhotoImage(excel_icon)
def save_to_excel():
output = get_system_info()
try:
# Открытие диалогового окна выбора директории
directory = filedialog.askdirectory()
if directory:
hostname = socket.gethostname()
timestamp = datetime.datetime.now().strftime("%d.%m.%H.%M")
workbook = openpyxl.Workbook()
worksheet = workbook.active
worksheet.title = "System Info"
rows = output.split("\n")
for row_index in range(len(rows)):
row = rows[row_index]
columns = row.split(":")
if len(columns) > 1:
key = columns[0].strip()
value = columns[1].strip()
worksheet.cell(row=row_index + 1, column=1, value=key)
worksheet.cell(row=row_index + 1, column=2, value=value)
# Расширение ширины колонки под текст
worksheet.column_dimensions['A'].width = len(key) + 15
worksheet.column_dimensions['B'].width = max(len(value) + 2,
worksheet.column_dimensions['B'].width)
workbook.save(filename=f"{directory}/{hostname}_{timestamp}.xlsx")
messagebox.showinfo("Успех", "Информация сохранена")
except Exception as e:
messagebox.showerror("Ошибка", f"Не удалось сохранить информацию: {e}")
save_to_excel_button = tk.Button(window, text="Сохранить в Excel", command=save_to_excel, image=excel_icon,
compound="left")
save_to_excel_button.configure(font=("Arial", 12), foreground="Black", background="SeaGreen")
save_to_excel_button.pack()
show_info_button.pack(side=tk.LEFT, padx=100)
save_to_txt_button.pack(side=tk.LEFT, padx=100)
save_to_excel_button.pack(side=tk.LEFT, padx=100)
window.mainloop()
# Запуск графического интерфейса
create_gui() |