用脚本导出系统服务列表

wen 实用脚本 2

本文目录导读:

用脚本导出系统服务列表

  1. Windows 系统
  2. Linux 系统
  3. macOS 系统
  4. 通用导出脚本(跨平台)
  5. 使用说明

Windows 系统

PowerShell 脚本

# 导出所有服务列表到CSV文件
Get-Service | Select-Object Status, Name, DisplayName, ServiceType, StartType | Export-Csv -Path "C:\services_list.csv" -NoTypeInformation -Encoding UTF8
# 更详细的版本(包含更多信息)
Get-WmiObject Win32_Service | Select-Object Name, DisplayName, State, StartMode, PathName, ProcessId, Description | Export-Csv -Path "C:\services_detailed.csv" -NoTypeInformation -Encoding UTF8
# 导出到文本文件
Get-Service | Format-Table -AutoSize | Out-File -FilePath "C:\services_list.txt" -Width 200 -Encoding UTF8

CMD 脚本 (services_export.bat)

@echo off
:: 导出服务列表
sc query state= all > "C:\services_list.txt"
:: 带详细信息的导出
sc query state= all | findstr /i "SERVICE_NAME DISPLAY_NAME STATE" > "C:\services_detailed.txt"
echo 服务列表已导出到 C:\services_list.txt

Linux 系统

Bash 脚本

#!/bin/bash
# 导出所有系统服务
echo "=== 系统服务列表 ===" > /tmp/services_list.txt
echo "导出时间: $(date)" >> /tmp/services_list.txt
echo "=====================" >> /tmp/services_list.txt
# 对于 systemd 系统
if command -v systemctl &> /dev/null; then
    systemctl list-units --type=service --all >> /tmp/services_list.txt
    systemctl list-unit-files --type=service >> /tmp/services_list.txt
    # 导出到CSV格式
    echo -e "UNIT\tLOAD\tACTIVE\tSUB\tDESCRIPTION" > /tmp/services_list.csv
    systemctl list-units --type=service --all --no-legend | awk '{print $1"\t"$2"\t"$3"\t"$4"\t"$5}' >> /tmp/services_list.csv
fi
# 对于 SysV init 系统
if [ -d "/etc/init.d" ]; then
    echo -e "\n=== SysV 服务 ===" >> /tmp/services_list.txt
    ls /etc/init.d/ >> /tmp/services_list.txt
    # 查看运行状态
    service --status-all >> /tmp/services_list.txt 2>/dev/null
fi
echo -e "\n=== 服务状态详情 ===" >> /tmp/services_list.txt
if command -v netstat &> /dev/null; then
    netstat -tlnp >> /tmp/services_list.txt 2>/dev/null
fi
echo "服务列表已导出到 /tmp/services_list.txt"
# 创建CSV版本的脚本
cat > /tmp/export_services.sh << 'EOF'
#!/bin/bash
# 导出为CSV格式
{
    echo "服务名称,状态,类型,描述"
    systemctl list-units --type=service --all --no-legend | while read -r unit load active sub desc; do
        echo "$unit,$active,$sub,$desc"
    done
} > /tmp/services_list.csv
EOF
chmod +x /tmp/export_services.sh

macOS 系统

Bash 脚本

#!/bin/bash
# 导出launchd服务列表
echo "=== macOS 服务列表 ===" > ~/Desktop/services_list.txt
echo "导出时间: $(date)" >> ~/Desktop/services_list.txt
echo "=====================" >> ~/Desktop/services_list.txt
# 系统级 LaunchDaemons
echo -e "\n### 系统级 Daemons ###" >> ~/Desktop/services_list.txt
ls /Library/LaunchDaemons/ >> ~/Desktop/services_list.txt
# 系统级 LaunchAgents
echo -e "\n### 系统级 Agents ###" >> ~/Desktop/services_list.txt
ls /Library/LaunchAgents/ >> ~/Desktop/services_list.txt
# 用户级 LaunchAgents
echo -e "\n### 用户级 Agents ###" >> ~/Desktop/services_list.txt
ls ~/Library/LaunchAgents/ 2>/dev/null >> ~/Desktop/services_list.txt
# 正在运行的进程服务
echo -e "\n### 正在运行的进程 ###" >> ~/Desktop/services_list.txt
ps aux | grep -E "/(System|usr)/Library/" >> ~/Desktop/services_list.txt
# 导出为CSV格式
{
    echo "服务名称,类型,路径"
    for dir in "/Library/LaunchDaemons" "/Library/LaunchAgents" "$HOME/Library/LaunchAgents"; do
        if [ -d "$dir" ]; then
            for file in "$dir"/*.plist; do
                if [ -f "$file" ]; then
                    echo "$(basename "$file"),$(basename "$dir"),$file"
                fi
            done
        fi
    done
} > ~/Desktop/services_list.csv
echo "服务列表已导出到 ~/Desktop/services_list.txt 和 services_list.csv"

通用导出脚本(跨平台)

#!/usr/bin/env python3
"""跨平台服务列表导出脚本"""
import platform
import subprocess
import json
import csv
import datetime
def get_windows_services():
    """获取Windows服务列表"""
    try:
        result = subprocess.run(
            ['powershell', '-Command', 
             'Get-WmiObject Win32_Service | Select-Object Name, DisplayName, State, StartMode, PathName | ConvertTo-Json'],
            capture_output=True, text=True, check=True
        )
        return json.loads(result.stdout)
    except:
        return []
def get_linux_services():
    """获取Linux服务列表"""
    services = []
    try:
        result = subprocess.run(
            ['systemctl', 'list-units', '--type=service', '--all', '--no-legend'],
            capture_output=True, text=True, check=True
        )
        for line in result.stdout.strip().split('\n'):
            parts = line.split()
            if parts:
                services.append({
                    'name': parts[0],
                    'state': parts[3] if len(parts) > 3 else '',
                    'description': ' '.join(parts[4:]) if len(parts) > 4 else ''
                })
    except:
        pass
    return services
def export_services():
    """导出服务列表"""
    system = platform.system()
    if system == 'Windows':
        services = get_windows_services()
    elif system == 'Linux':
        services = get_linux_services()
    elif system == 'Darwin':  # macOS
        services = get_macos_services()
    else:
        services = []
    # 生成文件名
    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    json_file = f"services_{timestamp}.json"
    csv_file = f"services_{timestamp}.csv"
    # 导出JSON
    with open(json_file, 'w', encoding='utf-8') as f:
        json.dump({
            'system': system,
            'export_time': str(datetime.datetime.now()),
            'services': services
        }, f, indent=2, ensure_ascii=False)
    # 导出CSV
    if services:
        headers = list(services[0].keys()) if services else ['name', 'state', 'description']
        with open(csv_file, 'w', newline='', encoding='utf-8') as f:
            writer = csv.DictWriter(f, fieldnames=headers)
            writer.writeheader()
            writer.writerows(services)
    print(f"服务列表已导出:")
    print(f"  JSON: {json_file}")
    print(f"  CSV: {csv_file}")
if __name__ == "__main__":
    export_services()

使用说明

  1. Windows系统: 右键以管理员身份运行PowerShell或CMD脚本
  2. Linux系统:
    chmod +x services_export.sh
    ./services_export.sh
  3. macOS系统: 直接运行即可 包含:
  • 服务名称(Service Name)
  • 显示名称(Display Name)
  • 服务状态(Running/Stopped)
  • 启动类型(Automatic/Manual/Disabled)
  • 服务路径(Path)
  • 进程ID(PID)
  • 服务描述(Description)

您可以根据需要选择适合您系统的脚本,需要其他格式或特定过滤条件吗?

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