当前位置: 代码网 > it编程>前端脚本>Python > Python制作一个系统信息采集工具

Python制作一个系统信息采集工具

2024年12月19日 Python 我要评论
图样原码# 系统信息采集工具# 2024-12-16# 作者:hoye# 版本:1.0# 功能:采集系统信息并保存到文件# 使用方法:# 1. 运行程序# 2. 点击“采集系统信息”按钮# 3. 等待

图样

原码

# 系统信息采集工具
# 2024-12-16
# 作者:hoye
# 版本:1.0
# 功能:采集系统信息并保存到文件
# 使用方法:
# 1. 运行程序
# 2. 点击“采集系统信息”按钮
# 3. 等待信息采集完成
# 4. 选择保存位置
# 5. 点击“保存信息”按钮
 
 
import win32print
import socket
import subprocess
import win32com.shell.shell as shell
import win32com.shell.shellcon as shellcon
import wmi
from datetime import date
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext, filedialog
from threading import thread
import os
 
class systeminfoapp:
    def __init__(self, root):
        self.root = root
        self.root.title("蓝动力电脑-系统信息采集工具")
        self.root.geometry("800x600")
        
        # 设置整体样式
        style = ttk.style()
        style.configure('tbutton', padding=5)
        style.configure('tlabel', padding=5)
        
        self.create_widgets()
        
    def create_widgets(self):
        # 创建主框架
        main_frame = ttk.frame(self.root, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.w, tk.e, tk.n, tk.s))
        
        # 创建按钮框架
        button_frame = ttk.frame(main_frame)
        button_frame.grid(row=0, column=0, pady=5, sticky=tk.w)
        
        # 采集按钮
        self.collect_btn = ttk.button(
            button_frame, 
            text="采集系统信息", 
            command=self.start_collection
        )
        self.collect_btn.grid(row=0, column=0, padx=5)
        
        # 保存按钮
        self.save_btn = ttk.button(
            button_frame, 
            text="保存信息", 
            command=self.save_info
        )
        self.save_btn.grid(row=0, column=1, padx=5)
        
        # 进度条
        self.progress = ttk.progressbar(
            main_frame, 
            orient=tk.horizontal, 
            length=300, 
            mode='determinate'
        )
        self.progress.grid(row=1, column=0, pady=5, sticky=tk.ew)
        
        # 信息显示区域
        self.info_text = scrolledtext.scrolledtext(
            main_frame, 
            width=80, 
            height=30, 
            wrap=tk.word
        )
        self.info_text.grid(row=2, column=0, pady=5, sticky=(tk.w, tk.e, tk.n, tk.s))
        
        # 状态标签
        self.status_label = ttk.label(main_frame, text="就绪")
        self.status_label.grid(row=3, column=0, pady=5, sticky=tk.w)
        
        # 设置列和行的权重
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        main_frame.columnconfigure(0, weight=1)
        main_frame.rowconfigure(2, weight=1)
 
    def get_basic_info(self):
        """获取基本系统信息"""
        info = []
        self.update_status("正在获取基本系统信息...")
        computer_name = socket.gethostname()
        try:
            s = socket.socket(socket.af_inet, socket.sock_dgram)
            s.connect(("8.8.8.8", 80))
            ip_address = s.getsockname()[0]
            s.close()
        except exception as e:
            ip_address = "无法获取ip地址"
        
        info.extend([
            "=== 基本系统信息 ===",
            f"计算机名: {computer_name}",
            f"ip 地址: {ip_address}",
            ""
        ])
        return info
 
    def get_printer_info(self):
        """获取打印机信息"""
        self.update_status("正在获取打印机信息...")
        try:
            printers = win32print.enumprinters(win32print.printer_enum_local, none, 1)
            info = ["=== 打印机信息 ==="]
            info.extend([f"打印机名称: {printer[2]}" for printer in printers])
            info.append("")
            return info
        except exception:
            return ["=== 打印机信息 ===", "无法获取打印机信息", ""]
 
    def get_hardware_info(self):
        """获取硬件信息"""
        self.update_status("正在获取硬件信息...")
        try:
            c = wmi.wmi()
            info = []
            
            # 计算机系统信息
            info.append("=== 计算机系统信息 ===")
            for computer in c.win32_computersystem():
                info.extend([
                    f"计算机名称: {computer.name}",
                    f"制造商: {computer.manufacturer}",
                    f"型号: {computer.model}",
                    ""
                ])
            
            # cpu信息
            info.append("=== cpu信息 ===")
            for processor in c.win32_processor():
                info.extend([
                    f"cpu型号: {processor.name}",
                    f"cpu id: {processor.processorid}",
                    f"cpu核心数: {processor.numberofcores}",
                    f"cpu线程数: {processor.numberoflogicalprocessors}",
                    ""
                ])
            
            # 硬盘信息
            info.append("=== 硬盘信息 ===")
            for disk in c.win32_diskdrive():
                size_gb = round(int(disk.size or 0) / (1024**3), 2)
                info.extend([
                    f"硬盘型号: {disk.model}",
                    f"硬盘序列号: {disk.serialnumber}",
                    f"硬盘容量: {size_gb}gb",
                    ""
                ])
 
            return info
        except exception as e:
            return ["=== 硬件信息 ===", f"获取硬件信息出错: {str(e)}", ""]
 
    def get_folder_paths(self):
        """获取重要文件夹路径"""
        self.update_status("正在获取系统文件夹路径...")
        try:
            desktop = shell.shgetfolderpath(0, shellcon.csidl_desktop, 0, 0)
            documents = shell.shgetfolderpath(0, shellcon.csidl_personal, 0, 0)
            info = [
                "=== 系统文件夹路径 ===",
                f"桌面位置: {desktop}",
                f"我的文档位置: {documents}",
                ""
            ]
            return info
        except exception as e:
            return ["=== 系统文件夹路径 ===", "无法获取文件夹路径", str(e), ""]
 
    def get_network_shares(self):
        """获取网络共享信息"""
        self.update_status("正在获取网络共享信息...")
        try:
            output = subprocess.check_output("net share", shell=true, text=true)
            info = [
                "=== 网络共享信息 ===",
                output,
                ""
            ]
            return info
        except subprocess.calledprocesserror as e:
            return ["=== 网络共享信息 ===", f"获取网络共享信息出错: {str(e)}", ""]
 
    def collect_info(self):
        """收集所有系统信息"""
        self.progress["value"] = 0
        self.info_text.delete(1.0, tk.end)
        
        all_info = []
        
        # 获取基本信息
        all_info.extend(self.get_basic_info())
        self.progress["value"] = 20
        
        # 获取文件夹路径
        all_info.extend(self.get_folder_paths())
        self.progress["value"] = 35
        
        # 获取打印机信息
        all_info.extend(self.get_printer_info())
        self.progress["value"] = 50
        
        # 获取硬件信息
        all_info.extend(self.get_hardware_info())
        self.progress["value"] = 75
        
        # 获取网络共享信息
        all_info.extend(self.get_network_shares())
        self.progress["value"] = 100
        
        # 显示信息
        self.info_text.insert(tk.end, "\n".join(all_info))
        self.update_status("信息采集完成")
 
    def start_collection(self):
        """在新线程中启动信息收集"""
        self.collect_btn["state"] = "disabled"
        thread(target=self.collect_info, daemon=true).start()
        self.collect_btn["state"] = "normal"
 
    def save_info(self):
        """保存信息到文件"""
        if not self.info_text.get(1.0, tk.end).strip():
            messagebox.showwarning("警告", "没有可保存的信息,请先采集系统信息")
            return
        
        try:
            date_str = date.today().strftime("%y-%m-%d")
            computer_name = socket.gethostname()
            
            # 默认文件名
            default_filename = f"{computer_name}_info_{date_str}.txt"
            
            # 创建保存选项按钮框架
            save_window = tk.toplevel(self.root)
            save_window.title("选择保存位置")
            save_window.geometry("300x200")
            save_window.transient(self.root)  # 设置为主窗口的子窗口
            
            def save_to_network():
                try:
                    network_path = f"\\\\bpc\\temp_g\\{default_filename}"
                    with open(network_path, "w", encoding="utf-8") as f:
                        f.write(self.info_text.get(1.0, tk.end))
                    messagebox.showinfo("成功", f"信息已保存到网络位置:\n{network_path}")
                    save_window.destroy()
                except exception as e:
                    messagebox.showerror("错误", f"保存到网络位置失败:\n{str(e)}")
            
            def save_to_local():
                initial_dir = os.path.expanduser("~\\documents")  # 默认打开我的文档
                filename = filedialog.asksaveasfilename(
                    parent=save_window,
                    initialdir=initial_dir,
                    initialfile=default_filename,
                    defaultextension=".txt",
                    filetypes=[("文本文件", "*.txt"), ("所有文件", "*.*")]
                )
                if filename:
                    try:
                        with open(filename, "w", encoding="utf-8") as f:
                            f.write(self.info_text.get(1.0, tk.end))
                        messagebox.showinfo("成功", f"信息已保存到:\n{filename}")
                        save_window.destroy()
                    except exception as e:
                        messagebox.showerror("错误", f"保存文件时出错:\n{str(e)}")
            
            def save_to_d_drive():
                try:
                    # 确保d盘存在
                    if not os.path.exists("d:\\"):
                        messagebox.showerror("错误", "未找到d盘")
                        return
                    
                    # 在d盘根目录创建文件
                    d_drive_path = f"d:\\{default_filename}"
                    with open(d_drive_path, "w", encoding="utf-8") as f:
                        f.write(self.info_text.get(1.0, tk.end))
                    messagebox.showinfo("成功", f"信息已保存到:\n{d_drive_path}")
                    save_window.destroy()
                except exception as e:
                    messagebox.showerror("错误", f"保存到d盘失败:\n{str(e)}")
            
            # 创建保存选项按钮
            ttk.label(
                save_window, 
                text="请选择保存位置:", 
                padding=10
            ).pack()
            
            ttk.button(
                save_window,
                text="保存到网络位置(\\\\bpc\\temp_g)",
                command=save_to_network,
                padding=5
            ).pack(pady=5, padx=10, fill=tk.x)
            
            ttk.button(
                save_window,
                text="保存到d盘",
                command=save_to_d_drive,
                padding=5
            ).pack(pady=5, padx=10, fill=tk.x)
            
            ttk.button(
                save_window,
                text="保存到本地位置",
                command=save_to_local,
                padding=5
            ).pack(pady=5, padx=10, fill=tk.x)
            
            # 居中显示窗口
            save_window.update_idletasks()
            width = save_window.winfo_width()
            height = save_window.winfo_height()
            x = (save_window.winfo_screenwidth() // 2) - (width // 2)
            y = (save_window.winfo_screenheight() // 2) - (height // 2)
            save_window.geometry(f'{width}x{height}+{x}+{y}')
            
            # 模态对话框
            save_window.grab_set()
            save_window.focus_set()
            
        except exception as e:
            messagebox.showerror("错误", f"创建保存对话框时出错:\n{str(e)}")
 
    def update_status(self, message):
        """更新状态栏消息"""
        self.status_label["text"] = message
        self.root.update()
 
def main():
    root = tk.tk()
    app = systeminfoapp(root)
    root.mainloop()
 
if __name__ == "__main__":
    main()

打包 exe

pip install pyinstaller

version_info.txt

# utf-8
#
# for more details about fixed file info 'ffi' see:
# http://msdn.microsoft.com/en-us/library/ms646997.aspx
vsversioninfo(
  ffi=fixedfileinfo(
    # filevers和prodvers应该始终是包含4个项的元组
    filevers=(1, 0, 0, 0),
    prodvers=(1, 0, 0, 0),
    # 包含一个位掩码,指定文件的有效信息
    mask=0x3f,
    # 包含一个位掩码,指定布尔属性的文件
    flags=0x0,
    # 操作系统
    os=0x40004,
    # 文件类型
    filetype=0x1,
    # 文件子类型
    subtype=0x0,
    # 创建日期
    date=(0, 0)
    ),
  kids=[
    stringfileinfo(
      [
      stringtable(
        '080404b0',
        [stringstruct('companyname', '蓝动力电脑'),
        stringstruct('filedescription', '系统信息采集工具'),
        stringstruct('fileversion', '1.0.0'),
        stringstruct('internalname', 'systeminfocollector'),
        stringstruct('legalcopyright', 'copyright (c) 2024 hoye'),
        stringstruct('originalfilename', 'systeminfocollector.exe'),
        stringstruct('productname', '系统信息采集工具'),
        stringstruct('productversion', '1.0.0')])
      ]), 
    varfileinfo([varstruct('translation', [2052, 1200])])
    ]
) 

build.py

import pyinstaller.__main__
import os
 
# 确保当前工作目录正确
current_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(current_dir)
 
pyinstaller.__main__.run([
    '7_系统信息采集工具.py',
    '--name=systeminfocollector',
    '--windowed',
    # '--icon=app.ico',  # 如果您有图标文件的话
    '--version-file=version_info.txt',
    '--clean',
    '--noconfirm',
    '--uac-admin',  # 添加管理员权限
    '--onefile',    # 打包成单一文件
    f'--workpath={os.path.join(current_dir, "build")}',
    f'--distpath={os.path.join(current_dir, "dist")}',
    f'--specpath={current_dir}'
]) 

python build.py

到此这篇关于python制作一个系统信息采集工具的文章就介绍到这了,更多相关python系统信息采集内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com