怎么用脚本获取系统组件列表

wen 实用脚本 1

本文目录导读:

怎么用脚本获取系统组件列表

  1. Windows系统
  2. Linux系统
  3. macOS系统
  4. 跨平台Python脚本
  5. 输出格式示例
  6. 使用建议

我来介绍几种获取系统组件列表的方法,根据不同的操作系统和需求选择:

Windows系统

PowerShell脚本

# 获取已安装的Windows功能
Get-WindowsOptionalFeature -Online | Select-Object FeatureName, State
# 获取系统服务
Get-Service | Select-Object Name, DisplayName, Status
# 获取已安装的程序(注册表方式)
Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | 
    Select-Object DisplayName, DisplayVersion, Publisher | 
    Where-Object {$_.DisplayName -ne $null} | 
    Sort-Object DisplayName

CMD脚本

@echo off
echo ===== Windows组件列表 =====
dism /online /get-features /format:table
echo.
echo ===== 已安装服务 =====
sc query type= service state= all

Linux系统

Bash脚本

#!/bin/bash
# 1. 获取已安装的软件包(Debian/Ubuntu)
echo "===== APT软件包 ====="
dpkg --list | awk '{print $2}' 
# 2. 获取已安装的软件包(RHEL/CentOS)
echo "===== RPM软件包 ====="
rpm -qa --qf "%{NAME}\n"
# 3. 获取系统服务列表
echo "===== SystemD服务 ====="
systemctl list-units --type=service --all
# 4. 获取内核模块
echo "===== 内核模块 ====="
lsmod | awk '{print $1}'
# 5. 获取硬件组件
echo "===== PCI设备 ====="
lspci
echo "===== USB设备 ====="
lsusb

更详细的软件包列表

#!/bin/bash
# 获取所有已安装软件包(使用yum/dnf)
yum list installed | awk '{print $1}' > installed_packages.txt
# 或者使用Python脚本
python3 -c "
import subprocess
import sys
def get_installed_packages():
    if sys.platform.startswith('linux'):
        # 尝试多种包管理器
        try:
            result = subprocess.run(['dpkg', '--list'], capture_output=True, text=True)
            if result.returncode == 0:
                for line in result.stdout.split('\n'):
                    if line.startswith('ii'):
                        parts = line.split()
                        if len(parts) >= 2:
                            print(f'Package: {parts[1]}')
        except:
            pass
        try:
            result = subprocess.run(['rpm', '-qa'], capture_output=True, text=True)
            if result.returncode == 0:
                for line in result.stdout.split('\n'):
                    if line.strip():
                        print(f'Package: {line.strip()} | Version: {line.split(\"-\")[-1]}')
        except:
            pass
get_installed_packages()
"

macOS系统

#!/bin/bash
# 获取Homebrew安装的软件
echo "===== Homebrew软件 ====="
brew list --formula
# 获取系统应用
echo "===== 系统应用 ====="
ls /Applications/
# 获取系统扩展
echo "===== 系统扩展 ====="
systemextensionsctl list

跨平台Python脚本

#!/usr/bin/env python3
import subprocess
import platform
import json
def get_windows_components():
    """获取Windows组件列表"""
    components = []
    # 使用PowerShell获取系统服务
    try:
        result = subprocess.run([
            'powershell.exe', 
            '-Command', 
            'Get-Service | Select-Object Name, DisplayName, Status | ConvertTo-Json'
        ], capture_output=True, text=True)
        if result.returncode == 0:
            services = json.loads(result.stdout)
            components.append({"type": "services", "items": services})
    except:
        pass
    return components
def get_linux_components():
    """获取Linux组件列表"""
    components = []
    # 获取系统服务
    try:
        result = subprocess.run(['systemctl', 'list-units', '--type=service'], 
                              capture_output=True, text=True)
        services = [line.split() for line in result.stdout.split('\n') if line.strip()]
        components.append({"type": "services", "items": services})
    except:
        pass
    # 获取已安装软件包
    try:
        result = subprocess.run(['dpkg', '--list'], capture_output=True, text=True)
        packages = []
        for line in result.stdout.split('\n'):
            if line.startswith('ii'):
                parts = line.split()
                if len(parts) >= 2:
                    packages.append({"name": parts[1], "version": parts[2]})
        components.append({"type": "packages", "items": packages})
    except:
        pass
    return components
def main():
    system = platform.system()
    print(f"操作系统: {system}")
    if system == "Windows":
        components = get_windows_components()
    elif system == "Linux":
        components = get_linux_components()
    else:
        print("其他系统,需要手动处理")
        return
    # 输出到JSON文件
    with open('system_components.json', 'w', encoding='utf-8') as f:
        json.dump(components, f, ensure_ascii=False, indent=2)
    # 输出到CSV文件(仅示例)
    import csv
    with open('system_components.csv', 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow(['类型', '名称', '版本/状态'])
        for comp in components:
            for item in comp['items']:
                writer.writerow([comp['type'], item.get('name', ''), item.get('version', '')])
if __name__ == "__main__":
    main()

输出格式示例

使用脚本后,可以生成:

  • JSON格式:适合程序解析
  • CSV格式:适合在Excel中查看
  • 文本格式:适合人工阅读
  • 数据库:如果要保存历史记录

使用建议

  1. 根据需求选择脚本

    • 想快速查看:用简单的命令行
    • 需要详细记录:用Python脚本生成结构化文件
    • 需要实时监控:添加定时任务
  2. 权限要求

    • 部分命令需要管理员权限(sudo/admin)
    • 确保脚本有合适的权限运行
  3. 性能优化

    • 大批量查询时使用并行处理
    • 使用缓存机制避免重复查询

选择哪种方式取决于你的具体需求和操作系统环境,需要我针对某个特定场景提供更详细的脚本吗?

抱歉,评论功能暂时关闭!