文章总结: 该文档展示了一个WindowsServer2022系统的Python自动化巡检报告,详细记录了系统基本信息、运行时间、KMS激活状态、硬件资源(CPU、内存、磁盘)、网络配置、进程服务、安全更新及用户登录情况。报告显示系统运行正常但存在磁盘使用率数据异常(负值)和KMS激活剩余168天的问题,建议检查磁盘配置并及时更换正版授权以确保系统合规性。 综合评分: 60 文章分类: 安全运营,终端安全,安全工具,技术标准,其他
Windows 系统Python一键巡检报告
原创
刘军军 刘军军
运维星火燎原
2026年4月1日 00:02 天津
在小说阅读器读本章
去阅读
1.系统基本信息
os_name: Windows
os_version: 10.0.20348
os_release: 2022Server
os_architecture: 64bit
machine_type: AMD64
hostname: liujunjun-Workstation
fqdn: locahost
username: Administrator
userdomain: LIUJUNJUN-WORKS
processor_architecture: AMD64
number_of_processors: 4
2.系统运行时间
boot_time: 2026-03-3118:08:13
uptime_days: 0
uptime_hours: 0
uptime_minutes: 53
uptime_seconds: 3201
3.许可证与激活状态
license_info:
名称: Windows(R), ServerDatacenteredition
描述: Windows(R) OperatingSystem, VOLUME_KMSCLIENTchannel
部分产品密钥: 6VM33
许可证状态: 已授权
批量激活过期: 240781 分钟(168 天)
已配置的激活类型: KMS
最新激活信息:
密钥管理服务客户端信息
客户端计算机 ID (CMID):8cd65b8f-f2f8-4c49-b185-67ea71ddfcf8
已注册的 KMS 计算机名称: kms.03k.org:1688
KMS 计算机 IP 地址: 1.12.54.119
KMS 计算机扩展的 PID: 03612-00206-561-097806-03-2052-17763.0000-1562020
激活时间间隔: 43200 分钟
续订间隔: 43200 分钟
已启用 KMS 主机缓存
4.处理器信息
cpu_details:
LoadPercentage: 10
Manufacturer: GenuineIntel
MaxClockSpeed: 2601
Name: Intel(R) Core(TM) i3-10110U CPU @ 2.10GHz
NumberOfCores: 2
NumberOfLogicalProcessors: 4
5.内存信息
total_memory_gb:7.78
total_memory_kb:8157312
free_memory_gb:1.21
free_memory_kb:1271580
used_memory_gb:6.57
memory_percent:84.4
memory_chips:
Capacity Manufacturer PartNumber Speed
85899345920000 DDR4 NB 8G 2666 2667
6.磁盘存储信息
partitions: 3 项
[1]
device_id: 本地固定磁盘
volume_name: C:
description:
size_gb: 69.63
free_gb: 132.37
used_gb: -62.74
used_percent: -90.1
[2]
device_id: 本地固定磁盘
volume_name: D:
description: 新加卷
size_gb: 84.99
free_gb: 97.66
used_gb: -12.67
used_percent: -14.9
[3]
device_id: 本地固定磁盘
volume_name: E:
description: E
size_gb: 134.72
free_gb: 245.66
used_gb: -110.94
used_percent: -82.3
7.网络配置信息
ipconfig:
WindowsIP 配置
主机名 . . . . . . . . . . . . . : liujunjun-Workstation
主 DNS 后缀 . . . . . . . . . . . :
节点类型 . . . . . . . . . . . . : 混合
IP 路由已启用 . . . . . . . . . . : 否
WINS 代理已启用 . . . . . . . . . : 否
以太网适配器 vEthernet (NpcapLoopbackAdapter-VirtualSwitch):
连接特定的 DNS 后缀 . . . . . . . :
描述. . . . . . . . . . . . . . . : Hyper-VVirtualEthernetAdapter
物理地址. . . . . . . . . . . . . : 02-00-4C-4F-4F-50
DHCP 已启用 . . . . . . . . . . . : 是
自动配置已启用. . . . . . . . . . : 是
本地链接 IPv6 地址. . . . . . . . : fe80::5065:4d51:49a7:3f23%15(首选)
自动配置 IPv4 地址 . . . . . . . : 169.254.20.44(首选)
子网掩码 . . . . . . . . . . . . : 255.255.0.0
默认网关. . . . . . . . . . . . . :
DHCPv6IAID . . . . . . . . . . . : 386007116
DHCPv6 客户端 DUID . . . . . . . : 00-01-00-01-29-C6-FE-49-90-2E-16-5B-43-98
DNS 服务器 . . . . . . . . . . . : fec0:0:0:ffff::1%1
fec0:0:0:ffff::2%1
fec0:0:0...
established_connections: 18 项
[1]TCP 192.168.1.252:62879 101.36.166.11:443ESTABLISHED
[2]TCP 192.168.1.252:62885 111.62.113.101:443ESTABLISHED
[3]TCP 192.168.1.252:62896 101.91.111.161:80ESTABLISHED
[4]TCP 192.168.1.252:62899 111.32.211.186:443ESTABLISHED
[5]TCP 192.168.1.252:62906 111.32.210.113:443ESTABLISHED
[6]TCP 192.168.1.252:62923 111.62.37.139:443ESTABLISHED
[7]TCP 192.168.1.252:62936 111.31.56.90:443ESTABLISHED
[8]TCP 192.168.1.252:62938 4.145.79.82:443ESTABLISHED
[9]TCP 192.168.1.252:62941 112.90.80.96:443ESTABLISHED
[10]TCP 192.168.1.252:63010 111.62.37.139:443ESTABLISHED
[11]TCP 192.168.1.252:63046 111.62.37.140:443ESTABLISHED
[12]TCP 192.168.1.252:63054 111.62.37.139:443ESTABLISHED
[13]TCP 192.168.1.252:63103 111.62.113.77:443ESTABLISHED
[14]TCP 192.168.1.252:63211 4.145.79.82:443ESTABLISHED
[15]TCP 192.168.1.252:63276 111.30.170.28:8081ESTABLISHED
[16]TCP[2409:8a02:b42b:9960:4624:46c3:e584:c158]:62898[2409:8c02:24c:90:3::f]:443ESTABLISHED
[17]TCP[2409:8a02:b42b:9960:4624:46c3:e584:c158]:63034[2409:8c02:24c:90:3::f]:443ESTABLISHED
[18]TCP[2409:8a02:b42b:9960:4624:46c3:e584:c158]:63129[2408:4001:f10::3e5]:443 ESTABLISHED
8.进程与服务状态
processes:
"映像名称","PID","会话名 ","会话# ","内存使用 "
"System Idle Process","0","Services","0","8 K"
"System","4","Services","0","152 K"
"Registry","116","Services","0","65,260 K"
"smss.exe","428","Services","0","1,300 K"
"csrss.exe","676","Services","0","6,688 K"
"wininit.exe","756","Services","0","7,180 K"
"csrss.exe","776","Console","1","7,276 K"
"winlogon.exe","848","Console","1","11,376 K"
"services.exe","856","Services","0","11,156 K"
"lsass.exe","912","Services","0","19,052 K"
"svchost.exe","324","Services","0","29,436 K"
"fontdrvhost.exe","628","Console","1","39,280 K"
"fontdrvhost.exe","632","Services","0","14,708 K"
"WUDFHost.exe","968","Services","0","5,756 K"
"svchost.exe","1064","Services","0","13,104 K"
"svchost.exe","1124","Services","0","11,572 K"
"WUDFHost.exe","1160","Services","0","7,564 K"
"svchost.exe","1312","Services","0","13,168 K"
"svchost.exe","1352","Services","0","5,632 K"
"svchost.exe","1360","Services","0","12,220 K"
"svchost.exe","1460","Services","0","12,492 K"
"svc...
9.安全与更新
updates:
Description HotFixID InstalledOn
Update KB5066139 10/31/2025
SecurityUpdate KB5012170 1/2/2023
Update KB5014831 11/22/2022
SecurityUpdate KB5078766 3/16/2026
SecurityUpdate KB5078763 3/16/2026
SecurityUpdate KB5034439 2/6/2024
firewall_status:
域配置文件 设置:
----------------------------------------------------------------------
状态 启用
专用配置文件 设置:
----------------------------------------------------------------------
状态 启用
公用配置文件 设置:
----------------------------------------------------------------------
状态 启用
确定。
10.用户与登录
local_users:
\\LIUJUNJUN-WORKS 的用户帐户
-------------------------------------------------------------------------------
Administrator DefaultAccount Guest
WDAGUtilityAccount
命令成功完成。
current_logins:
用户名 会话名 ID 状态 空闲时间 登录时间
>administrator console 1 运行中 无 2026/3/3118:08
user_groups:
\\LIUJUNJUN-WORKS 的别名
-------------------------------------------------------------------------------
*__vmware__
*Access Control Assistance Operators
*Administrators
*Backup Operators
*Certificate Service DCOM Access
*Cryptographic Operators
*Device Owners
*Distributed COM Users
*Event Log Readers
*Guests
*Hyper-V Administrators
*IIS_IUSRS
*Network Configuration Operators
*Performance Log Users
*Performance Monitor Users
*Power Users
*Print Operators
*RDS Endpoint Servers
*RDS Management Servers
*RDS Remote Access Servers
*Remote Desktop Users
*Remote Management Users
*Replicator
*Storage Replica Administrators
*System Managed Accounts Group
*Users
*WSUS Administrators
*WSUS Reporters
命令成功完成。
11.系统日志(最近24小时)
system_error_logs:
Event[0]
Log Name: System
Source: VBoxNetLwf
Date: 2026-01-12T15:27:51.0590000Z
Event ID: 12
Task: N/A
Level: 错误
Opcode: N/A
Keyword: 经典
User: N/A
User Name: N/A
Computer: liujunjun-Workstation
Description:
驱动程序在 \Device\VBoxNetLwf 上检测到内部驱动程序错误。
Event[1]
Log Name: System
Source: Microsoft-Windows-Ntfs
Date: 2026-01-12T15:27:53.4960000Z
Event ID: 98
Task: N/A
Level: 错误
Opcode: 信息
Keyword: N/A
User: S-1-5-18
User Name: NT AUTHORITY\SYSTEM
Computer: liujunjun-Workstation
Description:
卷 \\?\Volume{b7becba5-b167-4de7-bfcf-c793bf610e04} (\Device\HarddiskVolume6) 需要脱机一段时间以执行完整的 Chkdsk。请在本机通过命令行运行 "CHKDSK /F",或者在本机或远程通过 PowerShell 运行 "REPAIR-VOLUME <驱动器:>"。
Event[2]
Log Name: System
Source: Service Control Manager
Date: 2026-01-12T15:27:55.4100000Z
Event ID: 7000
Task: N/A
Level: 错误
Opcode: N/A
Keyword: 经典
User: N/A
User Name: N/A
Computer: liujunjun-Workstation
Description:
由于下列错误,luafv 服务启动失败:
此驱动程序被阻止加载
Event[...
application_error_logs:
Event[0]
Log Name: Application
Source: Application Error
Date: 2026-01-02T16:10:31.7650000Z
Event ID: 1000
Task: 应用程序崩溃事件
Level: 错误
Opcode: 信息
Keyword: 经典
User: N/A
User Name: N/A
Computer: liujunjun-Workstation
Description:
错误应用程序名称: JZDLLCatchTip.exe,版本: 2.0.0.0,时间戳: 0x68946f81
错误模块名称: JZDLLCatchTip.exe,版本: 2.0.0.0,时间戳: 0x68946f81
异常代码: 0xc0000005
错误偏移量: 0x0007a851
错误进程 ID: 0x21964
错误应用程序启动时间: 0x01dc7bbf438e7aa8
错误应用程序路径: E:\qudong\JZDriver\JZDLLCatchTip.exe
错误模块路径: E:\qudong\JZDriver\JZDLLCatchTip.exe
报告 ID: 358edc02-f646-4b6d-a076-adda978e9db9
错误程序包全名:
错误程序包相对应用程序 ID:
Event[1]
Log Name: Application
Source: Application Error
Date: 2026-01-02T16:10:33.7350000Z
Event ID: 1000
Task: 应用程序崩溃事件
Level: 错误
Opcode: 信息
Keyword: 经典
User: N/A
User Name: N/A
Computer: liujunjun-Workstation
Description:
错误应用程序名称: JZDLLCatchTip.exe,版本: 2.0.0.0,时间戳: 0x68946f81
错误模块名称: JZDLLCatchTip.exe,版本: 2.0.0.0,时间戳: 0x68946f81
异常代码: 0xc0000005
错误偏移量: 0x...
12.性能指标
cpu_percent:13
network_stats:
接口统计
接收的 发送的
字节 78221853052067139
单播数据包 586434300372
非单播数据包 3306560
丢弃 00
错误 00
未知协议 0
13.Python脚本
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Windows 系统一键巡检脚本
Python 3.x 版本
"""
import os
import sys
import platform
import socket
import datetime
import subprocess
import json
import csv
from typing import Dict, List, Any, Optional
defcheck_os() -> bool:
"""检查是否为Windows系统"""
return os.name == 'nt'
defrun_command(cmd: str, capture_output: bool = True, shell: bool = True) -> Dict[str, Any]:
"""执行系统命令"""
try:
result = subprocess.run(
cmd,
capture_output=capture_output,
text=True,
shell=shell,
timeout=30
)
return {
'success': result.returncode == 0,
'returncode': result.returncode,
'stdout': result.stdout,
'stderr': result.stderr
}
except Exception as e:
return {
'success': False,
'error': str(e)
}
defget_system_info() -> Dict[str, Any]:
"""获取系统基本信息"""
info = {}
info['os_name'] = platform.system()
info['os_version'] = platform.version()
info['os_release'] = platform.release()
info['os_architecture'] = platform.architecture()[0]
info['machine_type'] = platform.machine()
info['hostname'] = socket.gethostname()
try:
info['fqdn'] = socket.getfqdn()
except Exception:
info['fqdn'] = 'N/A'
info['username'] = os.environ.get('USERNAME', 'N/A')
info['userdomain'] = os.environ.get('USERDOMAIN', 'N/A')
info['processor_architecture'] = os.environ.get('PROCESSOR_ARCHITECTURE', 'N/A')
info['number_of_processors'] = os.environ.get('NUMBER_OF_PROCESSORS', 'N/A')
return info
defget_uptime() -> Dict[str, Any]:
"""获取系统运行时间"""
info = {}
try:
result = run_command('wmic os get lastbootuptime /value')
if result['success'] and result['stdout']:
for line in result['stdout'].strip().split('\n'):
if'='in line:
key, value = line.split('=', 1)
if key.strip() == 'LastBootUpTime':
boot_time_str = value.strip()
if len(boot_time_str) >= 14:
try:
year = boot_time_str[0:4]
month = boot_time_str[4:6]
day = boot_time_str[6:8]
hour = boot_time_str[8:10]
minute = boot_time_str[10:12]
second = boot_time_str[12:14]
boot_time = datetime.datetime(
int(year), int(month), int(day),
int(hour), int(minute), int(second)
)
current_time = datetime.datetime.now()
uptime = current_time - boot_time
info['boot_time'] = boot_time.strftime('%Y-%m-%d %H:%M:%S')
info['uptime_days'] = uptime.days
info['uptime_hours'] = int(uptime.total_seconds() // 3600)
info['uptime_minutes'] = int(uptime.total_seconds() // 60)
info['uptime_seconds'] = int(uptime.total_seconds())
except Exception as e:
info['parse_error'] = str(e)
except Exception as e:
info['error'] = str(e)
return info
defget_license_status() -> Dict[str, Any]:
"""获取许可证与激活状态"""
info = {}
try:
slmgr_path = os.path.join(os.environ.get('SystemRoot', 'C:\\Windows'), 'System32', 'slmgr.vbs')
if os.path.exists(slmgr_path):
result = run_command(f'cscript //Nologo "{slmgr_path}" /dli')
if result['success']:
info['license_info'] = result['stdout'].strip()
else:
info['license_info'] = '无法获取许可证信息(可能需要管理员权限)'
else:
info['license_info'] = '未找到许可证管理工具'
except Exception as e:
info['error'] = str(e)
return info
defget_processor_info() -> Dict[str, Any]:
"""获取处理器信息"""
info = {}
try:
result = run_command('wmic cpu get name,manufacturer,maxclockspeed,numberofcores,numberoflogicalprocessors,loadpercentage /format:list')
if result['success']:
cpu_info = {}
for line in result['stdout'].strip().split('\n'):
if'='in line:
key, value = line.split('=', 1)
cpu_info[key.strip()] = value.strip()
info['cpu_details'] = cpu_info
except Exception as e:
info['error'] = str(e)
return info
defget_memory_info() -> Dict[str, Any]:
"""获取内存信息"""
info = {}
try:
result = run_command('wmic computersystem get totalphysicalmemory /value')
if result['success']:
for line in result['stdout'].strip().split('\n'):
if'='in line:
key, value = line.split('=', 1)
if key.strip() == 'TotalPhysicalMemory':
total_bytes = int(value.strip())
info['total_memory_gb'] = round(total_bytes / (1024**3), 2)
info['total_memory_kb'] = total_bytes // 1024
result = run_command('wmic os get freephysicalmemory /value')
if result['success']:
for line in result['stdout'].strip().split('\n'):
if'='in line:
key, value = line.split('=', 1)
if key.strip() == 'FreePhysicalMemory':
free_kb = int(value.strip())
info['free_memory_gb'] = round(free_kb * 1024 / (1024**3), 2)
info['free_memory_kb'] = free_kb
if'total_memory_gb'in info and'free_memory_gb'in info:
info['used_memory_gb'] = round(info['total_memory_gb'] - info['free_memory_gb'], 2)
info['memory_percent'] = round((info['used_memory_gb'] / info['total_memory_gb']) * 100, 1)
result = run_command('wmic memorychip get capacity,speed,manufacturer,partnumber /format:table')
if result['success']:
info['memory_chips'] = result['stdout'].strip()
except Exception as e:
info['error'] = str(e)
return info
defget_disk_info() -> Dict[str, Any]:
"""获取磁盘存储信息"""
info = {}
info['partitions'] = []
try:
result = run_command('wmic logicaldisk get deviceid,volumename,size,freespace,description /format:csv')
if result['success']:
lines = result['stdout'].strip().split('\n')
for line in lines[1:]:
if line.strip():
parts = line.split(',')
if len(parts) >= 5:
device_id = parts[1].strip('"')
volume_name = parts[2].strip('"')
size = parts[3].strip('"')
free_space = parts[4].strip('"')
description = parts[5].strip('"') if len(parts) > 5else''
partition = {
'device_id': device_id,
'volume_name': volume_name,
'description': description
}
try:
if size:
size_bytes = int(size)
partition['size_gb'] = round(size_bytes / (1024**3), 2)
if free_space:
free_bytes = int(free_space)
partition['free_gb'] = round(free_bytes / (1024**3), 2)
if'size_gb'in partition:
partition['used_gb'] = round(partition['size_gb'] - partition['free_gb'], 2)
partition['used_percent'] = round((partition['used_gb'] / partition['size_gb']) * 100, 1)
except Exception:
pass
info['partitions'].append(partition)
except Exception as e:
info['error'] = str(e)
return info
defget_network_info() -> Dict[str, Any]:
"""获取网络配置信息"""
info = {}
try:
result = run_command('ipconfig /all')
if result['success']:
info['ipconfig'] = result['stdout']
result = run_command('netstat -an')
if result['success']:
established_connections = []
for line in result['stdout'].split('\n'):
if'ESTABLISHED'in line:
established_connections.append(line.strip())
info['established_connections'] = established_connections[:20]
except Exception as e:
info['error'] = str(e)
return info
defget_process_service_status() -> Dict[str, Any]:
"""获取进程与服务状态"""
info = {}
try:
result = run_command('tasklist /fo csv')
if result['success']:
info['processes'] = result['stdout'].strip()
result = run_command('sc query type= service state= running')
if result['success']:
info['running_services'] = result['stdout'].strip()
except Exception as e:
info['error'] = str(e)
return info
defget_security_updates() -> Dict[str, Any]:
"""获取安全与更新状态"""
info = {}
try:
result = run_command('wmic qfe get hotfixid,installedon,description /format:table')
if result['success']:
info['updates'] = result['stdout'].strip()
result = run_command('netsh advfirewall show allprofiles state')
if result['success']:
info['firewall_status'] = result['stdout'].strip()
else:
result = run_command('netsh firewall show state')
if result['success']:
info['firewall_status'] = result['stdout'].strip()
except Exception as e:
info['error'] = str(e)
return info
defget_users_login() -> Dict[str, Any]:
"""获取用户与登录信息"""
info = {}
try:
result = run_command('net user')
if result['success']:
info['local_users'] = result['stdout'].strip()
result = run_command('quser')
ifnot result['success']:
result = run_command('query user')
if result['success']:
info['current_logins'] = result['stdout'].strip()
else:
info['current_logins'] = '无法获取登录信息(可能需要管理员权限)'
result = run_command('net localgroup')
if result['success']:
info['user_groups'] = result['stdout'].strip()
except Exception as e:
info['error'] = str(e)
return info
defget_system_logs() -> Dict[str, Any]:
"""获取系统日志(最近24小时)"""
info = {}
try:
result = run_command('wevtutil qe System /q:"*[System[Level=2]]" /f:text /c:10')
if result['success']:
info['system_error_logs'] = result['stdout'].strip()
else:
info['system_error_logs'] = '需要管理员权限查看日志或wevtutil工具不可用'
result = run_command('wevtutil qe Application /q:"*[System[Level=2]]" /f:text /c:10')
if result['success']:
info['application_error_logs'] = result['stdout'].strip()
else:
info['application_error_logs'] = '需要管理员权限查看日志或wevtutil工具不可用'
except Exception as e:
info['error'] = str(e)
return info
defget_performance_metrics() -> Dict[str, Any]:
"""获取性能指标"""
info = {}
try:
result = run_command('wmic cpu get loadpercentage /value')
if result['success']:
for line in result['stdout'].strip().split('\n'):
if'='in line:
key, value = line.split('=', 1)
if key.strip() == 'LoadPercentage':
info['cpu_percent'] = value.strip()
result = run_command('netstat -e')
if result['success']:
info['network_stats'] = result['stdout'].strip()
except Exception as e:
info['error'] = str(e)
return info
defprint_section(title: str, data: Dict[str, Any]):
"""打印章节内容"""
print(f"\n{'=' * 60}")
print(f" {title}")
print('=' * 60)
defprint_dict(d: Dict, indent: int = 0):
for key, value in d.items():
prefix = ' ' * indent
if isinstance(value, dict):
print(f"{prefix}{key}:")
print_dict(value, indent + 2)
elif isinstance(value, list):
print(f"{prefix}{key}: {len(value)} 项")
for i, item in enumerate(value[:5]):
if isinstance(item, dict):
print(f"{prefix} [{i+1}]")
print_dict(item, indent + 4)
else:
print(f"{prefix} [{i+1}] {item}")
if len(value) > 5:
print(f"{prefix} ... 等 {len(value) - 5} 项")
elif isinstance(value, str) and len(value) > 500:
print(f"{prefix}{key}:")
print(f"{prefix} {value[:500]}...")
else:
print(f"{prefix}{key}: {value}")
print_dict(data)
defwrite_dict_to_file(f, d: Dict, indent: int = 0):
"""将字典写入文件"""
for key, value in d.items():
prefix = ' ' * indent
if isinstance(value, dict):
f.write(f"{prefix}{key}:\n")
write_dict_to_file(f, value, indent + 2)
elif isinstance(value, list):
f.write(f"{prefix}{key}: {len(value)} 项\n")
for i, item in enumerate(value):
if isinstance(item, dict):
f.write(f"{prefix} [{i+1}]\n")
write_dict_to_file(f, item, indent + 4)
else:
f.write(f"{prefix} [{i+1}] {item}\n")
elif isinstance(value, str):
if len(value) > 1000:
f.write(f"{prefix}{key}:\n{prefix} {value[:1000]}...\n")
else:
lines = value.split('\n')
if len(lines) > 1:
f.write(f"{prefix}{key}:\n")
for line in lines:
f.write(f"{prefix} {line}\n")
else:
f.write(f"{prefix}{key}: {value}\n")
else:
f.write(f"{prefix}{key}: {value}\n")
defgenerate_report(data: Dict[str, Any], section_titles: Dict[str, str]):
"""生成TXT格式报告文件"""
timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
report_file = f"System_Inspection_Report_{timestamp}.txt"
with open(report_file, 'w', encoding='utf-8') as f:
# 写入报告标题
f.write("=" * 60 + "\n")
f.write(" Windows 系统一键巡检报告\n")
f.write("=" * 60 + "\n")
f.write(f"报告时间: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write(f"Python版本: {platform.python_version()}\n")
f.write("=" * 60 + "\n\n")
# 写入各章节内容
for key, title in section_titles.items():
f.write("\n" + "=" * 60 + "\n")
f.write(f" {title}\n")
f.write("=" * 60 + "\n\n")
write_dict_to_file(f, data[key])
f.write("\n" + "=" * 60 + "\n")
f.write(" 巡检完成\n")
f.write("=" * 60 + "\n")
print(f"\n{'=' * 60}")
print(f"巡检报告已保存到: {report_file}")
return report_file
defmain():
"""主函数"""
print("=" * 60)
print(" Windows 系统一键巡检脚本")
print("=" * 60)
print(f"开始巡检: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print()
ifnot check_os():
print("错误: 此脚本仅适用于Windows操作系统")
input("\n按回车键退出...")
return
inspection_data = {
'system_info': get_system_info(),
'uptime': get_uptime(),
'license_status': get_license_status(),
'processor_info': get_processor_info(),
'memory_info': get_memory_info(),
'disk_info': get_disk_info(),
'network_info': get_network_info(),
'process_service_status': get_process_service_status(),
'security_updates': get_security_updates(),
'users_login': get_users_login(),
'system_logs': get_system_logs(),
'performance_metrics': get_performance_metrics()
}
section_titles = {
'system_info': '1. 系统基本信息',
'uptime': '2. 系统运行时间',
'license_status': '3. 许可证与激活状态',
'processor_info': '4. 处理器信息',
'memory_info': '5. 内存信息',
'disk_info': '6. 磁盘存储信息',
'network_info': '7. 网络配置信息',
'process_service_status': '8. 进程与服务状态',
'security_updates': '9. 安全与更新',
'users_login': '10. 用户与登录',
'system_logs': '11. 系统日志(最近24小时)',
'performance_metrics': '12. 性能指标'
}
for key, title in section_titles.items():
print_section(title, inspection_data[key])
generate_report(inspection_data, section_titles)
print("\n" + "=" * 60)
print(f"巡检完成: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("=" * 60)
input("\n按回车键退出...")
if __name__ == '__main__':
main()
- Python版本3.13,可以在cmd中直接执行。
- 也可以在PyCharm中直接执行。输出会保存在一个txt文本中。
免责声明:
本文所载程序、技术方法仅面向合法合规的安全研究与教学场景,旨在提升网络安全防护能力,具有明确的技术研究属性。
任何单位或个人未经授权,将本文内容用于攻击、破坏等非法用途的,由此引发的全部法律责任、民事赔偿及连带责任,均由行为人独立承担,本站不承担任何连带责任。
本站内容均为技术交流与知识分享目的发布,若存在版权侵权或其他异议,请通过邮件联系处理,具体联系方式可点击页面上方的联系我。
本文转载自:运维星火燎原 刘军军 刘军军《Windows 系统Python一键巡检报告》
版权声明
本站仅做备份收录,仅供研究与教学参考之用。
读者将信息用于其他用途的,全部法律及连带责任由读者自行承担,本站不承担任何责任。









![[紧急播报]突发!知名前端库<ahref="/cdn-cgi/l/email-protection"class="__cf_email__"data-cf](/images/random/titlepic/13.jpg)

评论