0%

Windows主机资产信息收集脚本

收集内容&&实现思路

系统信息[OS、IP 、补丁信息]、开放端口、服务、计划任务、自启动项、安装应用

系统信息

通过调用Powershell获取主机环境信息【不能用wmic 因为wmic可能需要高权限】

开放端口

netstat -ano 过滤出 Listening 或 Established的信息

暂时还不知道怎么去优化 后续看情况调整

服务

通过wmi获取主机中所有服务[running/stop]

计划任务

HKEY_LOCAL_MACHINENT下存在着各种计划任务

但是好像没法用python去读【或许是虚表 没法读】

所以考虑使用COM接口去请求 Schedule.Service ,但是这种方法只能获取部分计划任务,不完整

自启动项

# 读取 HKEY_CURRENT_USER

# 读取 HKEY_CURRENT_USER

# 读取 HKEY_LOCAL_MACHINE

# 读取 HKEY_LOCAL_MACHINE

安装应用

# 列出 HKLM下的子项及其 DisplayName 值

# 列出 HKCU下的子项及其 DisplayName 值

环境安装问题

可通过python3 调用命令行或查注册表键值对获取相关信息

在win2003中没有Powershell环境 要用py3或者bat脚本去获取信息【但是win2003支持python版本最高位python3.4 环境安装有问题】

需要提前安装相关库

pip install wmi

pip install pypiwin32

win10 win7 win2008 win2012 win2016测试下脚本均可行

win2012下 安装python3.7.0 后【选择添加环境变量 安装后自带pip】 可直接使用打包好的exe

运行脚本 缺少 vcruntime 但是在安装runtime时报错需要下载前置补丁 【解决参考https://blog.csdn.net/blog_user_zk/article/details/111040113】

依次安装 KB2939087 KB2975061 KB2919355 再安装VCRuntime即可

win2008 python可用3.7.0缺少 VCRUNTIME140_1.dll ... 需要安装runtime https://aka.ms/vs/17/release/vc_redist.x64.exe

win2003 python3.3.5【http://www.python.org/ftp/python/3.3.5/python-3.3.5.msi】 语法不支持 f相关 所以需要全改成format

win2003 pip安装有问题 还没解决。。。。。。。。。。。。。

换版本 https://www.python.org/ftp/python/3.4.4/python-3.4.4.msi 换成python3.4.4 自带pip

但是更新pip 后将不可用....

pip install pypiwin32,wmi 都不行 版本过低 所以不可用。 【pypiwin32只支持python3.5+】

Version1

Python3代码

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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# -*- coding: utf-8 -*-

import winreg
import win32com.client
import platform
import subprocess
import wmi

def get_startup_items(hive, subkey):
try:
key = winreg.OpenKey(hive, subkey, 0, winreg.KEY_READ)

startup_items = {}
index = 0

while True:
try:
name, value, _ = winreg.EnumValue(key, index)
startup_items[name] = value
index += 1
except OSError:
# 到达注册表末尾
break

return startup_items

except Exception as e:
print(f"Error: {e}")
return {}

# 读取 HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
startup_items_current_user_run = get_startup_items(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run")
# 读取 HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
startup_items_current_user_runonce = get_startup_items(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce")
# 读取 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
startup_items_local_machine_run = get_startup_items(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run")
# 读取 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
startup_items_local_machine_runonce = get_startup_items(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce")

# 打印自启动项
def print_startup_items(startup_items, title):
if startup_items:
print(f"[+] {title}:\n")
for name, value in startup_items.items():
print(f"Name: {name}")
# print(f"Path: {value}")
# print("-"*50)
else:
# print(f"{title} is empty.\n")
pass


def get_task_scheduler():
scheduler = win32com.client.Dispatch('Schedule.Service')
scheduler.Connect()
rootFolder = scheduler.GetFolder('\\')
return rootFolder

def print_tasks_info(root_folder):
for task in root_folder.GetTasks(0):
print(f"Task Name: {task.Name}")
print(f"Next Run Time: {task.NextRunTime}")
print(f"State: {task.State}")
print("-" * 50)

def get_services():
try:
c = wmi.WMI()
services = c.Win32_Service()
return services
except Exception as e:
print(f"Error: {e}")
return []



def list_registry_subkeys(hive, subkey):
try:
with winreg.OpenKey(hive, subkey) as key:
subkeys_count, _, _ = winreg.QueryInfoKey(key)
subkeys = [winreg.EnumKey(key, i) for i in range(subkeys_count)]
return subkeys
except Exception as e:
print(f"Error: {e}")
return []


def get_registry_value(hive, subkey, value_name):
try:
with winreg.OpenKey(hive, subkey) as key:
value, _ = winreg.QueryValueEx(key, value_name)
return value
except Exception as e:
# print(f"Error: {e}")
return None

def getSystemInfo():
print("[+] 获取系统信息、补丁信息......\n")
# 获取操作系统版本信息
os_version = platform.platform()
# 打印操作系统版本信息
print("操作系统版本:", os_version)
# 设置 PowerShell 脚本
powershell_script = """
# # 设置执行策略
# Set-ExecutionPolicy RemoteSigned -Force
#
# # 获取已安装的所有补丁信息
# $patches = Get-HotFix
# $patchCount = $patches.Count
# Write-Output "已安装的补丁数量: $patchCount"
#
# foreach ($patch in $patches) {
# # Write-Output "补丁号: $($patch.HotFixID) - 描述: $($patch.Description)"
# Write-Output "补丁号: $($patch.HotFixID) "
#
# }
# 设置输出编码为 UTF-8
$OutputEncoding = [System.Text.Encoding]::UTF8

# 设置执行策略
Set-ExecutionPolicy RemoteSigned -Force

# 获取主机名
$hostname = $env:COMPUTERNAME

# 打印主机名
Write-Host "主机名: $hostname"

# 获取 IP 地址信息
$ipInfo = Get-NetIPAddress | Where-Object { $_.AddressFamily -eq "IPv4" }

# 提取 IP 地址
$ipAddress = $ipInfo.IPAddress

# 打印 IP 地址
Write-Host "IP 地址: $ipAddress"

# 获取操作系统版本信息
$osVersion = [System.Environment]::OSVersion

# 获取操作系统名称
$osName = (Get-CimInstance Win32_OperatingSystem).Caption

# 打印操作系统名称
Write-Host "操作系统名称: $osName"

# 打印操作系统版本信息
Write-Host "操作系统版本: $($osVersion.VersionString)"

# 获取 Windows 版本号
$windowsVersion = "$($osVersion.Version.Major).$($osVersion.Version.Minor)"

# 打印 Windows 版本号
Write-Host "Windows 版本号: $windowsVersion"

# 获取已安装的所有补丁信息
$patches = Get-HotFix
$patchCount = $patches.Count
Write-Output "已安装的补丁数量: $patchCount"

foreach ($patch in $patches) {
Write-Output "补丁号: $($patch.HotFixID) - 描述: $($patch.Description)"
# Write-Output "补丁号: $($patch.HotFixID) "
}

"""

# 执行 PowerShell 脚本
# process = subprocess.Popen(["powershell", "-Command", powershell_script], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
process = subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-Command", powershell_script],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
output, error = process.communicate()
# 打印输出结果
print(output)
# 如果有错误,打印错误信息
# if error:
# print("错误信息:", error)
print("=" * 50)


def getInstallAppInfo():
print("[+] 获取主机已安装应用信息......\n")
#列出 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall 下的子项及其 DisplayName 值
hive1 = winreg.HKEY_LOCAL_MACHINE
subkey = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
subkeys1 = list_registry_subkeys(hive1, subkey)

hive2 = winreg.HKEY_CURRENT_USER
subkeys2 = list_registry_subkeys(hive2, subkey)
print("[=] HKLM:")
# 打印结果
for subkey_name in subkeys1:
subkey_path = fr"{subkey}\{subkey_name}"
display_name = get_registry_value(hive1, subkey_path, "DisplayName")

if display_name:
print(display_name)
# print(f"{subkey_name}: {display_name}")

else:
# print(f"{subkey_name}: Display Name not found.")
pass

print("-" * 50)
print("[=] HKCU:")

for subkey_name in subkeys2:
subkey_path = fr"{subkey}\{subkey_name}"
display_name = get_registry_value(hive2, subkey_path, "DisplayName")

if display_name:
print(display_name)
# print(f"{subkey_name}: {display_name}")

else:
# print(f"{subkey_name}: Display Name not found.")
pass
print("=" * 50)

def getAutoRunInfo():
print("[+] 获取主机启动项信息......\n")
print_startup_items(startup_items_current_user_run, "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run")
print_startup_items(startup_items_current_user_runonce, "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce")
print_startup_items(startup_items_local_machine_run, "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run")
print_startup_items(startup_items_local_machine_runonce, "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce")
print("=" * 50)

def getScheduleTaskInfo():
print("[+] 获取主机计划任务信息......[注:使用COM接口仅可获取部分]\n")
try:
root_folder = get_task_scheduler()
print_tasks_info(root_folder)
except Exception as e:
print(f"Error: {e}")
print("=" * 50)


def getServiceInfo():
print("[+] 获取主机服务信息......\n")
services = get_services()

# 打印服务信息
for service in services:
# 所有服务
print(f"Service Name: {service.Name}")
print(f"Display Name: {service.DisplayName}")
print(f"Status: {service.State}")
print("-" * 50)
print("=" * 50)


def getRunningServiceInfo():
print("[+] 获取主机正在运行的服务信息......\n")
services = get_services()

# 打印服务信息
for service in services:
# 只输出运行服务
if service.State == "Running":
print(f"Service Name: {service.Name}")
# print(f"Display Name: {service.DisplayName}")
# print(f"Status: {service.State}")
# print("==================================")
print("=" * 50)



def getPortInfo():
print("[+] 获取主机开放端口服务信息......\n")
try:
result = subprocess.run(["netstat", "-ano"], capture_output=True, text=True, check=True)
netstat_output = result.stdout

# 筛选出 LISTENING 或 ESTABLISHED 的行并输出
for line in netstat_output.splitlines():
if "LISTENING" in line or "ESTABLISHED" in line:
print(line)

except subprocess.CalledProcessError as e:
print(f"Error: {e}")
print("=" * 50)


def GetAllInfo():
getSystemInfo()
getAutoRunInfo()
getScheduleTaskInfo()
getInstallAppInfo()
# getServiceInfo()
getRunningServiceInfo()
getPortInfo()


if __name__ == '__main__':
GetAllInfo()

Output

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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
C:\Users\test\PycharmProjects\EncodeShellCode\venv\Scripts\python.exe C:\Users\test\PycharmProjects\EncodeShellCode\GetPCInfo\GetAllInfo.py 
[+] 获取系统信息、补丁信息......

操作系统版本: Windows-10-10.0.19045-SP0
主机名: DESKTOP-F3958O4
IP 地址: 192.168.181.141 127.0.0.1
操作系统名称: Microsoft Windows 10 专业版
操作系统版本: Microsoft Windows NT 10.0.19045.0
Windows 版本号: 10.0
已安装的补丁数量: 23
补丁号: KB5034466 - 描述: Update
补丁号: KB5030841 - 描述: Update
补丁号: KB5003791 - 描述: Update
补丁号: KB5011048 - 描述: Update
补丁号: KB5011050 - 描述: Update
补丁号: KB5012170 - 描述: Security Update
补丁号: KB5015684 - 描述: Update
补丁号: KB5034763 - 描述: Security Update
补丁号: KB5016705 - 描述: Update
补丁号: KB5020372 - 描述: Update
补丁号: KB5022924 - 描述: Update
补丁号: KB5023794 - 描述: Update
补丁号: KB5025315 - 描述: Update
补丁号: KB5026879 - 描述: Update
补丁号: KB5028318 - 描述: Update
补丁号: KB5028380 - 描述: Update
补丁号: KB5029709 - 描述: Update
补丁号: KB5031539 - 描述: Update
补丁号: KB5032392 - 描述: Update
补丁号: KB5032907 - 描述: Update
补丁号: KB5034224 - 描述: Update
补丁号: KB5005699 - 描述: Security Update
补丁号: KB5034441 - 描述: Security Update

==================================================
[+] 获取主机启动项信息......

[+] HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run:

Name: MicrosoftEdgeAutoLaunch_AF2BBCAD27A22A0C1234356BDE5EE233
[+] HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce:

Name: Application Restart #4
Name: Application Restart #7
Name: Application Restart #5
[+] HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run:

Name: SecurityHealth
Name: VMware User Process
Name: Everything
Name: Sysdiag
Name: KeePass 2 PreLoad
Name: DocFetcher-Daemon
==================================================
[+] 获取主机计划任务信息......[注:使用COM接口仅可获取部分]

Task Name: 360ZipUpdater
Next Run Time: 1899-12-30 00:00:00+00:00
State: 1
--------------------------------------------------
Task Name: OneDrive Reporting Task-S-1-5-21-2161087652-2094102714-1756561397-1000
Next Run Time: 2024-02-28 23:50:56+00:00
State: 3
--------------------------------------------------
Task Name: OneDrive Standalone Update Task-S-1-5-21-2161087652-2094102714-1756561397-1000
Next Run Time: 2024-02-28 22:52:37+00:00
State: 3
--------------------------------------------------
==================================================
[+] 获取主机已安装应用信息......

[=] HKLM:
Upscayl 2.8.6
7-Zip 23.01 (x64)
DocFetcher
Everything 1.4.1.1022 Lite (x64)
GIMP 2.10.34
Git
火绒安全软件
ImDisk Virtual Disk Driver
Mozilla Maintenance Service
WinRAR 6.21 (64-位)
Microsoft Visual C++ 2013 x64 Additional Runtime - 12.0.40664
Go Programming Language amd64 go1.20.4
Passware Kit Demo 2022 v2 (64-bit)
Microsoft Visual C++ 2010 x64 Redistributable - 10.0.40219
Python 3.9.13 Documentation (64-bit)
Microsoft Update Health Tools
VMware Tools
Microsoft Visual C++ 2022 X64 Additional Runtime - 14.31.30818
DiskGenius V5.5.1
Attribute Changer 11.10
Typora 1.1
Microsoft Visual C++ 2012 x64 Additional Runtime - 11.0.61135
Microsoft .NET Host - 6.0.27 (x64)
DiagnosticsHub_CollectionService
Windows SDK for Windows Store Apps DirectX x64 Remote
VS JIT Debugger
DB Browser for SQLite
Microsoft Visual C++ 2013 x64 Minimum Runtime - 12.0.40664
Microsoft Visual C++ 2022 X64 Minimum Runtime - 14.31.30818
IntelliTraceProfilerProxy
Microsoft Visual C++ 2008 Redistributable - x64 9.0.30729.7523
Python 3.9.13 Utility Scripts (64-bit)
Microsoft Visual Studio Team Foundation Server 2017 Update 9 Office Integration Language Pack (x64) - ENU
Application Verifier x64 External Package
Java SE Development Kit 8 Update 301 (64-bit)
Windows App Certification Kit Native Components
Microsoft Visual Studio Installer
Java 8 Update 401 (64-bit)
Python 3.9.13 pip Bootstrap (64-bit)
Microsoft .NET Host FX Resolver - 6.0.27 (x64)
Python 3.9.13 Test Suite (64-bit)
Microsoft .NET Runtime - 6.0.27 (x64)
Update for Windows 10 for x64-based Systems (KB5001716)
VS Script Debugging Common
Python 3.9.13 Standard Library (64-bit)
AccessData FTK Imager
ILSpy
Python 3.9.13 Development Libraries (64-bit)
Application Verifier x64 External Package
vs_Graphics_Singletonx64
Python 3.9.13 Add to Path (64-bit)
Mono for Windows (x64)
Microsoft Visual C++ 2012 x64 Minimum Runtime - 11.0.61135
Microsoft Visual Studio Team Foundation Server 2017 Update 9 Office Integration (x64)
Python 3.9.13 Executables (64-bit)
Python 3.9.13 Core Interpreter (64-bit)
Universal CRT Tools x64
icecap_collection_x64
Microsoft Windows Desktop Runtime - 6.0.27 (x64)
Python 3.9.13 Tcl/Tk Support (64-bit)
Windows SDK DirectX x64 Remote
Application Verifier x64 External Package (OnecoreUAP)
Application Verifier x64 External Package (DesktopEditions)
Microsoft Visual C++ 2017 X64 Debug Runtime - 14.16.27033
Microsoft System CLR Types for SQL Server vNext CTP1.6
--------------------------------------------------
[=] HKCU:
Clash for Windows 0.20.16
DBeaver 23.0.4 (current user)
Microsoft OneDrive
Rustup: the Rust toolchain installer
SageMath version 9.3
Python 3.9.13 (64-bit)
==================================================
[+] 获取主机正在运行的服务信息......

Service Name: Appinfo
Service Name: AudioEndpointBuilder
Service Name: Audiosrv
Service Name: BFE
Service Name: BrokerInfrastructure
Service Name: BthAvctpSvc
Service Name: CDPSvc
Service Name: COMSysApp
Service Name: CoreMessagingRegistrar
Service Name: CryptSvc
Service Name: DcomLaunch
Service Name: DeviceAssociationService
Service Name: Dhcp
Service Name: DiagTrack
Service Name: DispBrokerDesktopSvc
Service Name: Dnscache
Service Name: DoSvc
Service Name: DPS
Service Name: DsmSvc
Service Name: DsSvc
Service Name: DusmSvc
Service Name: EventLog
Service Name: EventSystem
Service Name: Everything
Service Name: fdPHost
Service Name: FDResPub
Service Name: FontCache
Service Name: HipsDaemon
Service Name: HRWSCCtrl
Service Name: ImDskSvc
Service Name: InstallService
Service Name: iphlpsvc
Service Name: IpOverUsbSvc
Service Name: KeyIso
Service Name: LanmanServer
Service Name: LanmanWorkstation
Service Name: LicenseManager
Service Name: lmhosts
Service Name: LSM
Service Name: mpssvc
Service Name: MSDTC
Service Name: NcbService
Service Name: NcdAutoSetup
Service Name: netprofm
Service Name: NlaSvc
Service Name: nsi
Service Name: PcaSvc
Service Name: phpStudySrv
Service Name: PlugPlay
Service Name: Power
Service Name: ProfSvc
Service Name: RasMan
Service Name: RmSvc
Service Name: RpcEptMapper
Service Name: RpcSs
Service Name: SamSs
Service Name: Schedule
Service Name: SecurityHealthService
Service Name: SENS
Service Name: SgrmBroker
Service Name: ShellHWDetection
Service Name: Spooler
Service Name: SSDPSRV
Service Name: SstpSvc
Service Name: StateRepository
Service Name: StorSvc
Service Name: SysMain
Service Name: Sysmon64
Service Name: SystemEventsBroker
Service Name: TabletInputService
Service Name: Themes
Service Name: TimeBrokerSvc
Service Name: TokenBroker
Service Name: TrkWks
Service Name: TrustedInstaller
Service Name: UserManager
Service Name: UsoSvc
Service Name: VaultSvc
Service Name: VGAuthService
Service Name: vm3dservice
Service Name: VMTools
Service Name: WaaSMedicSvc
Service Name: Wcmsvc
Service Name: WdiServiceHost
Service Name: WinHttpAutoProxySvc
Service Name: Winmgmt
Service Name: WpnService
Service Name: wscsvc
Service Name: WSearch
Service Name: wuauserv
Service Name: cbdhsvc_12655d
Service Name: CDPUserSvc_12655d
Service Name: OneSyncSvc_12655d
Service Name: WpnUserService_12655d
==================================================
[+] 获取主机开放端口服务信息......

TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 976
TCP 0.0.0.0:445 0.0.0.0:0 LISTENING 4
TCP 0.0.0.0:5040 0.0.0.0:0 LISTENING 3920
TCP 0.0.0.0:5357 0.0.0.0:0 LISTENING 4
TCP 0.0.0.0:7680 0.0.0.0:0 LISTENING 6336
TCP 0.0.0.0:7890 0.0.0.0:0 LISTENING 10996
TCP 0.0.0.0:49664 0.0.0.0:0 LISTENING 752
TCP 0.0.0.0:49665 0.0.0.0:0 LISTENING 592
TCP 0.0.0.0:49666 0.0.0.0:0 LISTENING 1148
TCP 0.0.0.0:49667 0.0.0.0:0 LISTENING 1428
TCP 0.0.0.0:49669 0.0.0.0:0 LISTENING 2732
TCP 0.0.0.0:49672 0.0.0.0:0 LISTENING 736
TCP 127.0.0.1:7890 127.0.0.1:54055 ESTABLISHED 10996
TCP 127.0.0.1:8888 0.0.0.0:0 LISTENING 9832
TCP 127.0.0.1:8888 127.0.0.1:50504 ESTABLISHED 9832
TCP 127.0.0.1:50049 0.0.0.0:0 LISTENING 10504
TCP 127.0.0.1:50050 0.0.0.0:0 LISTENING 10996
TCP 127.0.0.1:50050 127.0.0.1:50076 ESTABLISHED 10996
TCP 127.0.0.1:50065 127.0.0.1:50066 ESTABLISHED 9832
TCP 127.0.0.1:50066 127.0.0.1:50065 ESTABLISHED 9832
TCP 127.0.0.1:50076 127.0.0.1:50050 ESTABLISHED 10504
TCP 127.0.0.1:50482 127.0.0.1:50483 ESTABLISHED 9832
TCP 127.0.0.1:50483 127.0.0.1:50482 ESTABLISHED 9832
TCP 127.0.0.1:50491 0.0.0.0:0 LISTENING 5216
TCP 127.0.0.1:50491 127.0.0.1:50597 ESTABLISHED 5216
TCP 127.0.0.1:50492 0.0.0.0:0 LISTENING 5216
TCP 127.0.0.1:50492 127.0.0.1:50515 ESTABLISHED 5216
TCP 127.0.0.1:50492 127.0.0.1:50599 ESTABLISHED 5216
TCP 127.0.0.1:50493 0.0.0.0:0 LISTENING 5216
TCP 127.0.0.1:50493 127.0.0.1:50600 ESTABLISHED 5216
TCP 127.0.0.1:50494 0.0.0.0:0 LISTENING 5216
TCP 127.0.0.1:50495 0.0.0.0:0 LISTENING 5216
TCP 127.0.0.1:50495 127.0.0.1:50516 ESTABLISHED 5216
TCP 127.0.0.1:50495 127.0.0.1:50598 ESTABLISHED 5216
TCP 127.0.0.1:50496 127.0.0.1:50497 ESTABLISHED 9832
TCP 127.0.0.1:50497 127.0.0.1:50496 ESTABLISHED 9832
TCP 127.0.0.1:50498 127.0.0.1:50499 ESTABLISHED 9832
TCP 127.0.0.1:50499 127.0.0.1:50498 ESTABLISHED 9832
TCP 127.0.0.1:50500 127.0.0.1:50501 ESTABLISHED 9832
TCP 127.0.0.1:50501 127.0.0.1:50500 ESTABLISHED 9832
TCP 127.0.0.1:50502 127.0.0.1:50503 ESTABLISHED 9832
TCP 127.0.0.1:50503 127.0.0.1:50502 ESTABLISHED 9832
TCP 127.0.0.1:50504 127.0.0.1:8888 ESTABLISHED 9036
TCP 127.0.0.1:50515 127.0.0.1:50492 ESTABLISHED 9832
TCP 127.0.0.1:50516 127.0.0.1:50495 ESTABLISHED 9832
TCP 127.0.0.1:50520 127.0.0.1:50521 ESTABLISHED 5216
TCP 127.0.0.1:50521 127.0.0.1:50520 ESTABLISHED 5216
TCP 127.0.0.1:50522 127.0.0.1:50523 ESTABLISHED 5216
TCP 127.0.0.1:50523 127.0.0.1:50522 ESTABLISHED 5216
TCP 127.0.0.1:50524 127.0.0.1:50525 ESTABLISHED 5216
TCP 127.0.0.1:50525 127.0.0.1:50524 ESTABLISHED 5216
TCP 127.0.0.1:50526 127.0.0.1:50527 ESTABLISHED 5216
TCP 127.0.0.1:50527 127.0.0.1:50526 ESTABLISHED 5216
TCP 127.0.0.1:50528 127.0.0.1:50529 ESTABLISHED 5216
TCP 127.0.0.1:50529 127.0.0.1:50528 ESTABLISHED 5216
TCP 127.0.0.1:50530 127.0.0.1:50531 ESTABLISHED 5216
TCP 127.0.0.1:50531 127.0.0.1:50530 ESTABLISHED 5216
TCP 127.0.0.1:50532 127.0.0.1:50533 ESTABLISHED 5216
TCP 127.0.0.1:50533 127.0.0.1:50532 ESTABLISHED 5216
TCP 127.0.0.1:50534 127.0.0.1:50535 ESTABLISHED 5216
TCP 127.0.0.1:50535 127.0.0.1:50534 ESTABLISHED 5216
TCP 127.0.0.1:50536 127.0.0.1:50537 ESTABLISHED 5216
TCP 127.0.0.1:50537 127.0.0.1:50536 ESTABLISHED 5216
TCP 127.0.0.1:50538 0.0.0.0:0 LISTENING 5216
TCP 127.0.0.1:50539 127.0.0.1:50540 ESTABLISHED 5216
TCP 127.0.0.1:50540 127.0.0.1:50539 ESTABLISHED 5216
TCP 127.0.0.1:50541 127.0.0.1:50542 ESTABLISHED 5216
TCP 127.0.0.1:50542 127.0.0.1:50541 ESTABLISHED 5216
TCP 127.0.0.1:50543 127.0.0.1:50544 ESTABLISHED 5216
TCP 127.0.0.1:50544 127.0.0.1:50543 ESTABLISHED 5216
TCP 127.0.0.1:50545 127.0.0.1:50546 ESTABLISHED 5216
TCP 127.0.0.1:50546 127.0.0.1:50545 ESTABLISHED 5216
TCP 127.0.0.1:50547 127.0.0.1:50548 ESTABLISHED 5216
TCP 127.0.0.1:50548 127.0.0.1:50547 ESTABLISHED 5216
TCP 127.0.0.1:50549 127.0.0.1:50550 ESTABLISHED 5216
TCP 127.0.0.1:50550 127.0.0.1:50549 ESTABLISHED 5216
TCP 127.0.0.1:50587 127.0.0.1:50588 ESTABLISHED 5216
TCP 127.0.0.1:50588 127.0.0.1:50587 ESTABLISHED 5216
TCP 127.0.0.1:50589 127.0.0.1:50590 ESTABLISHED 9832
TCP 127.0.0.1:50590 127.0.0.1:50589 ESTABLISHED 9832
TCP 127.0.0.1:50591 127.0.0.1:50592 ESTABLISHED 9832
TCP 127.0.0.1:50592 127.0.0.1:50591 ESTABLISHED 9832
TCP 127.0.0.1:50593 127.0.0.1:50594 ESTABLISHED 9832
TCP 127.0.0.1:50594 127.0.0.1:50593 ESTABLISHED 9832
TCP 127.0.0.1:50595 127.0.0.1:50596 ESTABLISHED 9832
TCP 127.0.0.1:50596 127.0.0.1:50595 ESTABLISHED 9832
TCP 127.0.0.1:50597 127.0.0.1:50491 ESTABLISHED 9832
TCP 127.0.0.1:50598 127.0.0.1:50495 ESTABLISHED 9832
TCP 127.0.0.1:50599 127.0.0.1:50492 ESTABLISHED 9832
TCP 127.0.0.1:50600 127.0.0.1:50493 ESTABLISHED 9832
TCP 127.0.0.1:54055 127.0.0.1:7890 ESTABLISHED 9036
TCP 127.0.0.1:57752 0.0.0.0:0 LISTENING 8444
TCP 127.0.0.1:63342 0.0.0.0:0 LISTENING 8308
TCP 192.168.181.141:139 0.0.0.0:0 LISTENING 4
TCP 192.168.181.141:7890 192.168.181.1:56811 ESTABLISHED 10996
TCP 192.168.181.141:7890 192.168.181.1:56895 ESTABLISHED 10996
TCP 192.168.181.141:7890 192.168.181.1:56990 ESTABLISHED 10996
TCP 192.168.181.141:7890 192.168.181.1:57070 ESTABLISHED 10996
TCP 192.168.181.141:7890 192.168.181.1:57095 ESTABLISHED 10996
TCP 192.168.181.141:7890 192.168.181.1:57097 ESTABLISHED 10996
TCP 192.168.181.141:54026 183.236.51.24:10001 ESTABLISHED 10996
TCP 192.168.181.141:54039 58.254.149.166:443 ESTABLISHED 10996
TCP 192.168.181.141:54048 20.198.162.76:443 ESTABLISHED 3584
TCP 192.168.181.141:54049 183.236.51.24:10001 ESTABLISHED 10996
TCP 192.168.181.141:54056 183.236.51.24:10001 ESTABLISHED 10996
TCP 192.168.181.141:54057 183.236.51.24:10001 ESTABLISHED 10996
TCP 192.168.181.141:54061 183.236.51.24:10001 ESTABLISHED 10996
TCP 192.168.181.141:54062 183.236.51.24:10001 ESTABLISHED 10996
TCP [::]:135 [::]:0 LISTENING 976
TCP [::]:445 [::]:0 LISTENING 4
TCP [::]:5357 [::]:0 LISTENING 4
TCP [::]:7680 [::]:0 LISTENING 6336
TCP [::]:7890 [::]:0 LISTENING 10996
TCP [::]:49664 [::]:0 LISTENING 752
TCP [::]:49665 [::]:0 LISTENING 592
TCP [::]:49666 [::]:0 LISTENING 1148
TCP [::]:49667 [::]:0 LISTENING 1428
TCP [::]:49669 [::]:0 LISTENING 2732
TCP [::]:49672 [::]:0 LISTENING 736
TCP [::1]:8888 [::]:0 LISTENING 9832
==================================================

Process finished with exit code 0

Win2003

获取系统信息、IP、修复补丁信息
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
echo [+] 系统信息:
systeminfo | findstr /i /c:"主机名" /c:"OS 名称" /c:"OS 版本"

echo [+] IP地址:
for /f "tokens=2 delims=:" %%a in ('ipconfig ^| find "IP Address"') do echo %%a

echo [+] 列出已安装的修复补丁:
systeminfo | findstr /i /c:"修补程序:"

setlocal EnableDelayedExpansion

REM 运行 systeminfo 命令并将结果保存到临时文件
systeminfo > systeminfo_output.txt

REM 遍历文件内容
set "findPatch=false"
for /f "tokens=1,* delims=:" %%a in ('type systeminfo_output.txt') do (
REM 找到包含 "修补程序" 的行
if "!findPatch!"=="true" (
REM 输出当前行
echo %%a:%%b

REM 提取行中的数字
set "num=%%b"
set "num=!num:~1,1!"

REM 输出接下来的 X 行内容
for /l %%i in (1, 1, !num!) do (
set /p "outputLine="
echo !outputLine!
)

REM 设置标志为 false,表示不再继续寻找 "修补程序"
set "findPatch=false"
)

REM 找到 "修补程序" 行,设置标志为 true
if /i "%%a"=="修补程序" set "findPatch=true"
)

REM 删除临时文件
del systeminfo_output.txt

endlocal

Output

1
2
3
4
5
6
7
8
9
10
[+] 系统信息:
主机名: TEST-C52232A016
OS 名称: Microsoft(R) Windows(R) Server 2003, Enterprise Edition
OS 版本: 5.2.3790 Service Pack 2 Build 3790
BIOS 版本: INTEL - 6040000
[+] IP地址:
192.168.181.137
[+] 列出已安装的修复补丁:
修补程序: 安装了 1 个修补程序。
[01]: Q147222
查看安装的应用
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
@echo off
setlocal enabledelayedexpansion

echo [+] 列出 HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
for /f "tokens=*" %%a in ('reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" 2^>nul') do (
set "subkey=%%a"
set "display_name="

for /f "tokens=2,*" %%b in ('reg query "!subkey!" /v DisplayName 2^>nul ^| find "REG_SZ" 2^>nul') do (
set "display_name=%%c"
)

if defined display_name (
echo !display_name!
)
)

echo [+] 列出 HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
for /f "tokens=*" %%a in ('reg query "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" 2^>nul') do (
set "subkey=%%a"
set "display_name="

for /f "tokens=2,*" %%b in ('reg query "!subkey!" /v DisplayName 2^>nul ^| find "REG_SZ" 2^>nul') do (
set "display_name=%%c"
)

if defined display_name (
echo !display_name!
)
)

endlocal

Output

1
2
3
4
5
6
7
C:\Documents and Settings\Administrator\桌面>2.bat
[+] 列出 HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
Microsoft Visual C++ 2008 Redistributable - x86 9.0.30729.4148
Python 3.4.4
VMware Tools
[+] 列出 HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

正在运行的服务 net start
1
2
3
4
echo [+] 已经启动以下 Windows 服务:
echo --------------------------
net start
echo --------------------------

Output

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
[+] 已经启动以下 Windows 服务:
--------------------------
已经启动以下 Windows 服务:

Application Experience Lookup Service
Automatic Updates
COM+ Event System
COM+ System Application
Computer Browser
Cryptographic Services
DCOM Server Process Launcher
DHCP Client
Distributed Link Tracking Client
Distributed Transaction Coordinator
DNS Client
Error Reporting Service
Event Log
Help and Support
IPSEC Services
Logical Disk Manager
Network Connections
Network Location Awareness (NLA)
Plug and Play
Print Spooler
Protected Storage
Remote Procedure Call (RPC)
Remote Registry
Secondary Logon
Security Accounts Manager
Server
Shell Hardware Detection
System Event Notification
Task Scheduler
TCP/IP NetBIOS Helper
Terminal Services
TP AutoConnect Service
VMware Alias Manager and Ticket Service
VMware Tools
VMware 物理磁盘助手服务
Windows Management Instrumentation
Windows Time
Wireless Configuration
Workstation

命令成功完成。

--------------------------
计划任务
1
2
3
4
5
6
@echo off
echo Listing Scheduled Tasks...
echo --------------------------
schtasks /query /fo table
echo --------------------------

Output

1
2
3
4
Listing Scheduled Tasks...
--------------------------
信息: 系统里没有计划任务。
--------------------------
开放端口
1
2
3
4
echo Listing Open Ports...
echo ---------------------
netstat -ano | find "LISTENING"
echo ---------------------

Output

1
2
3
4
5
6
7
Listing Open Ports...
---------------------
TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 716
TCP 0.0.0.0:445 0.0.0.0:0 LISTENING 4
TCP 0.0.0.0:1027 0.0.0.0:0 LISTENING 428
TCP 192.168.181.137:139 0.0.0.0:0 LISTENING 4
---------------------
自启动项
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@echo off
echo Checking Registry Startup Items...
echo --------------------------------
echo [+] Current User Run:
reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" | findstr /i "REG_SZ"
echo --------------------------------
echo [+] Current User RunOnce:
reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce" | findstr /i "REG_SZ"
echo --------------------------------
echo [+] Local Machine Run:
reg query "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" | findstr /i "REG_SZ"
echo --------------------------------
echo [+] Local Machine RunOnce:
reg query "HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce" | findstr /i "REG_SZ"
echo --------------------------------

Output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Checking Registry Startup Items...
--------------------------------
[+] Current User Run:
ctfmon.exe REG_SZ C:\WINDOWS\system32\ctfmon.exe
--------------------------------
[+] Current User RunOnce:
--------------------------------
[+] Local Machine Run:
IMJPMIG8.1 REG_SZ "C:\WINDOWS\IME\imjp8_1\IMJPMIG.EXE" /Spoil /RemAdvD
ef /Migration32
IMEKRMIG6.1 REG_SZ C:\WINDOWS\ime\imkr6_1\IMEKRMIG.EXE
PHIME2002ASync REG_SZ C:\WINDOWS\system32\IME\TINTLGNT\TINTSETP.EXE /S
YNC
PHIME2002A REG_SZ C:\WINDOWS\system32\IME\TINTLGNT\TINTSETP.EXE /IMENa
me
VMware User Process REG_SZ "C:\Program Files\VMware\VMware Tools\vmtoo
lsd.exe" -n vmusr
--------------------------------
[+] Local Machine RunOnce:
--------------------------------

Win2003 bat脚本

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
@echo off

echo [+] 系统信息:
systeminfo | findstr /i /c:"主机名" /c:"OS 名称" /c:"OS 版本"

echo [+] IP地址:
for /f "tokens=2 delims=:" %%a in ('ipconfig ^| find "IP Address"') do echo %%a

echo [+] 列出已安装的修复补丁:
systeminfo | findstr /i /c:"修补程序:"

setlocal EnableDelayedExpansion

REM 运行 systeminfo 命令并将结果保存到临时文件
systeminfo > systeminfo_output.txt

REM 遍历文件内容
set "findPatch=false"
for /f "tokens=1,* delims=:" %%a in ('type systeminfo_output.txt') do (
REM 找到包含 "修补程序" 的行
if "!findPatch!"=="true" (
REM 输出当前行
echo %%a:%%b

REM 提取行中的数字
set "num=%%b"
set "num=!num:~1,1!"

REM 输出接下来的 X 行内容
for /l %%i in (1, 1, !num!) do (
set /p "outputLine="
echo !outputLine!
)

REM 设置标志为 false,表示不再继续寻找 "修补程序"
set "findPatch=false"
)

REM 找到 "修补程序" 行,设置标志为 true
if /i "%%a"=="修补程序" set "findPatch=true"
)

REM 删除临时文件
del systeminfo_output.txt

endlocal


setlocal enabledelayedexpansion

echo [+] 列出已安装的应用程序:
rem echo [+] 列出 HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
for /f "tokens=*" %%a in ('reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" 2^>nul') do (
set "subkey=%%a"
set "display_name="

for /f "tokens=2,*" %%b in ('reg query "!subkey!" /v DisplayName 2^>nul ^| find "REG_SZ" 2^>nul') do (
set "display_name=%%c"
)

if defined display_name (
echo !display_name!
)
)

rem echo [+] 列出 HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
for /f "tokens=*" %%a in ('reg query "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" 2^>nul') do (
set "subkey=%%a"
set "display_name="

for /f "tokens=2,*" %%b in ('reg query "!subkey!" /v DisplayName 2^>nul ^| find "REG_SZ" 2^>nul') do (
set "display_name=%%c"
)

if defined display_name (
echo !display_name!
)
)

endlocal

echo --------------------------
echo [+] 列出运行的服务:
net start
echo --------------------------

echo --------------------------
rem 这里需要管理员权限 普通用户没权限
schtasks /query /fo table
echo --------------------------

echo ---------------------
echo [+] 列出监听的端口:
netstat -ano | find "LISTENING"
echo ---------------------

echo [+] 列出主机中的自启动项:
echo --------------------------------
rem echo [+] Current User Run:
reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" | findstr /i "REG_SZ"
echo --------------------------------
rem echo [+] Current User RunOnce:
reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce" | findstr /i "REG_SZ"
echo --------------------------------
rem echo [+] Local Machine Run:
reg query "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" | findstr /i "REG_SZ"
echo --------------------------------
rem echo [+] Local Machine RunOnce:
reg query "HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce" | findstr /i "REG_SZ"
echo --------------------------------

schtasks /query /fo table 也需要管理员权限 所以存在问题 待完善

Output

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
C:\Documents and Settings\test123\桌面>1.bat
[+] 系统信息:
主机名: TEST-C52232A016
OS 名称: Microsoft(R) Windows(R) Server 2003, Enterprise Edition
OS 版本: 5.2.3790 Service Pack 2 Build 3790
BIOS 版本: INTEL - 6040000
[+] IP地址:
192.168.181.137
[+] 列出已安装的修复补丁:
修补程序: 安装了 1 个修补程序。
[01]: Q147222
[+] 列出已安装的应用程序:
Microsoft Visual C++ 2008 Redistributable - x86 9.0.30729.4148
Python 3.4.4
VMware Tools
--------------------------
已经启动以下 Windows 服务:

Application Experience Lookup Service
Automatic Updates
COM+ Event System
COM+ System Application
Computer Browser
Cryptographic Services
DCOM Server Process Launcher
DHCP Client
Distributed Link Tracking Client
Distributed Transaction Coordinator
DNS Client
Error Reporting Service
Event Log
Help and Support
IPSEC Services
Logical Disk Manager
Network Connections
Network Location Awareness (NLA)
Plug and Play
Print Spooler
Protected Storage
Remote Procedure Call (RPC)
Remote Registry
Secondary Logon
Security Accounts Manager
Server
Shell Hardware Detection
System Event Notification
Task Scheduler
TCP/IP NetBIOS Helper
Terminal Services
TP AutoConnect Service
VMware Alias Manager and Ticket Service
VMware Tools
VMware 物理磁盘助手服务
Windows Management Instrumentation
Windows Time
Wireless Configuration
Workstation

命令成功完成。

--------------------------
--------------------------
错误: 拒绝访问。
--------------------------
---------------------
TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 716
TCP 0.0.0.0:445 0.0.0.0:0 LISTENING 4
TCP 0.0.0.0:1027 0.0.0.0:0 LISTENING 428
TCP 192.168.181.137:139 0.0.0.0:0 LISTENING 4
---------------------
---------------------
[+] 列出主机中的自启动项:
--------------------------------
ctfmon.exe REG_SZ C:\WINDOWS\system32\ctfmon.exe
--------------------------------
--------------------------------
IMJPMIG8.1 REG_SZ "C:\WINDOWS\IME\imjp8_1\IMJPMIG.EXE" /Spoil /RemAdvD
ef /Migration32
IMEKRMIG6.1 REG_SZ C:\WINDOWS\ime\imkr6_1\IMEKRMIG.EXE
PHIME2002ASync REG_SZ C:\WINDOWS\system32\IME\TINTLGNT\TINTSETP.EXE /S
YNC
PHIME2002A REG_SZ C:\WINDOWS\system32\IME\TINTLGNT\TINTSETP.EXE /IMENa
me
VMware User Process REG_SZ "C:\Program Files\VMware\VMware Tools\vmtoo
lsd.exe" -n vmusr
--------------------------------
--------------------------------


Version2

考虑到全版本兼容 重新写了个 但是收集信息有限

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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# -*- coding: utf-8 -*-
import platform
import winreg
import re
import subprocess

service_port_mapping = {
21: "FTP/TFTP/VSFTPD (File Transfer Protocol)",
22: "SSH (Secure Shell)",
23: "Telnet (Remote Connection)",
25: "SMTP (Email)",
53: "DNS (Domain Name System)",
67: "DHCP (Dynamic Host Configuration Protocol)",
68: "DHCP (Dynamic Host Configuration Protocol)",
110: "POP3 (Email)",
123: "NTP",
135: "RPC(Remote Procedure Call)",
137: "Samba (File Sharing)",
139: "Samba (File Sharing)",
143: "IMAP (Email)",
161: "SNMP (Simple Network Management Protocol)",
389: "LDAP (Lightweight Directory Access Protocol)",
445: "SMB (Server Message Block)",
512: "Linux Rexec (Remote Execution Service)",
513: "Linux Rexec (Remote Execution Service)",
514: "Linux Rexec (Remote Execution Service)",
873: "Rsync (Remote File Synchronization)",
1080: "Socket",
1098: "JAVARMI",
1352: "Lotus Domino (Email)",
1433: "MSSQL (Microsoft SQL Server)",
1521: "Oracle Database",
2049: "NFS (Network File System)",
2181: "Zookeeper",
2222: "DA",
2375: "Docker Remote API",
2601: "zebra",
3306: "MySQL Database",
3128: "squid",
3389: "RDP (Remote Desktop Protocol)",
4100: "SysBase",
4440: "rundeck",
4848: "GlassFish Console",
5000: "Sybase/DB2 Database",
5422: "PostgreSQL Database",
5432: "PostgreSQL Database",
5632: "PCAnywhere Service",
5900: "VNC (Virtual Network Computing)",
5984: "CouchDB",
6082: "Varnish",
6379: "Redis Database",
7001: "WebLogic",
7002: "WebLogic",
80: "HTTP",
443: "HTTPS",
8000: "Jdwp",
8069: "Zabbix",
8161: "ActiveMQ",
8080: "Jboss/Tomcat/Resin/GlassFish/Jenkins/Jetty",
8089: "Jboss/Tomcat/Resin/GlassFish/Jenkins/Jetty",
8083: "InfluxDB",
8086: "InfluxDB",
8980: "OpenNMS",
9000: "FastCGI",
9080: "Websphere Console",
9090: "Websphere Console",
9200: "Elasticsearch",
9300: "Elasticsearch",
11211: "Memcached",
27017: "MongoDB",
27018: "MongoDB",
50000: "SAP",
50010: "Hadoop",
50030: "Hadoop",
50070: "Hadoop",

}

def get_startup_items(hive, subkey):
try:
key = winreg.OpenKey(hive, subkey, 0, winreg.KEY_READ)

startup_items = {}
index = 0

while True:
try:
name, value, _ = winreg.EnumValue(key, index)
startup_items[name] = value
index += 1
except OSError:
# 到达注册表末尾
break

return startup_items

except Exception as e:
# print("[-] Error: {}".format(e))
return {}

# 读取 HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
startup_items_current_user_run = get_startup_items(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run")
# 读取 HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
startup_items_current_user_runonce = get_startup_items(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce")
# 读取 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
startup_items_local_machine_run = get_startup_items(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run")
# 读取 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
startup_items_local_machine_runonce = get_startup_items(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce")

def print_startup_items(startup_items, title):
if startup_items:
print("[+] {}: ".format(title))
for name, value in startup_items.items():
print(name)
# print("Name: {}".format(name))
# print("Path: {}".format(value))
# print("-"*50)
else:
# print("{} is empty.\n".format(title))
pass

def list_registry_subkeys(hive, subkey):
try:
with winreg.OpenKey(hive, subkey) as key:
subkeys_count, _, _ = winreg.QueryInfoKey(key)
subkeys = [winreg.EnumKey(key, i) for i in range(subkeys_count)]
return subkeys
except Exception as e:
# print("[-] Error: {}".format(e))
return []

def get_registry_value(hive, subkey, value_name):
try:
with winreg.OpenKey(hive, subkey) as key:
value, _ = winreg.QueryValueEx(key, value_name)
return value
except Exception as e:
# print("[-] Error: {}".format(e))
return None

def getInstallAppInfo():
print("[+] 获取主机已安装应用信息......")
# 列出 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall 下的子项及其 DisplayName 值
hive1 = winreg.HKEY_LOCAL_MACHINE
subkey = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
subkeys1 = list_registry_subkeys(hive1, subkey)

hive2 = winreg.HKEY_CURRENT_USER
subkeys2 = list_registry_subkeys(hive2, subkey)
if subkeys1:
print("[+] HKLM:")

# 打印结果
for subkey_name in subkeys1:
subkey_path = r"{}\{}".format(subkey, subkey_name)
display_name = get_registry_value(hive1, subkey_path, "DisplayName")

if display_name:
print("{}".format(display_name))
else:
pass

# print("-" * 50)
if subkeys2:
print("[+] HKCU:")

for subkey_name in subkeys2:
subkey_path = r"{}\{}".format(subkey, subkey_name)
display_name = get_registry_value(hive2, subkey_path, "DisplayName")

if display_name:
print("{}".format(display_name))
else:
pass

print("=" * 50)

def getAutoRunInfo():
print("[+] 获取主机启动项信息......")
print_startup_items(startup_items_current_user_run, "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run")
print_startup_items(startup_items_current_user_runonce, "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce")
print_startup_items(startup_items_local_machine_run, "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run")
print_startup_items(startup_items_local_machine_runonce, "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce")
print("=" * 50)

def getPortInfo():
print("[+] 获取主机开放端口服务信息......")
services_found = [] # 保存识别出的端口服务信息
services_unfound = []
try:
result = subprocess.Popen(["netstat", "-ano"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, err = result.communicate()
netstat_output = out.decode('gbk')
# print(netstat_output)

# 使用正则表达式匹配并提取信息
for line in netstat_output.splitlines():
match = re.match(r'\s*TCP\s+(\S+)\s+(\S+)\s+(\S+)\s+(\d+)', line)
if match:
local_address, _, state, pid = match.groups()

# 只输出 LISTENING 状态的信息,并且只显示本地地址、状态和 PID
if state in ["LISTENING", "ESTABLISHED"]:
# 从 local_address 中提取 IP 地址和端口
ip_port_match = re.match(r'(\S+):(\d+)', local_address)
if ip_port_match:
ip, port = ip_port_match.groups()
# 尝试从字典中获取服务信息,如果没有找到则输出 "Unknown Service"
service = service_port_mapping.get(int(port), "Unknown Service")
# 输出 IP地址、端口、状态和 PID、服务
if service != "Unknown Service":
services_found.append({"port": port, "service": service})
else:
services_unfound.append({"port": port, "service": service})

# 本地连接IP 端口去重 并用port进行排序
services_found = [dict(t) for t in {tuple(d.items()) for d in services_found}]
services_found = sorted(services_found, key=lambda x: int(x['port']))

services_unfound = [dict(t) for t in {tuple(d.items()) for d in services_unfound}]
services_unfound = sorted(services_unfound, key=lambda x: int(x['port']))

print("[+] 共匹配到 {} 个已知端口服务".format(len(services_found)))
print("[+] 共匹配到 {} 个未知端口服务".format(len(services_unfound)))

print("[+] 识别出的端口服务:")
if services_found:
for service_info in services_found:
print(" {}\t\t{}".format(service_info['port'], service_info['service']))

print("[+] 未识别出的端口服务:")
if services_unfound:
for service_info in services_unfound:
print(" {}\t\t{}".format(service_info['port'], service_info['service']))

# 如果未找到相关信息,则输出一条消息
if not any(re.match(r'\s*TCP\s+(\S+)\s+(\S+)\s+(\S+)\s+(\d+)', line) for line in netstat_output.splitlines()):
print("[-] 未找到相关信息!")

except subprocess.CalledProcessError as e:
print("[-] 错误: {}".format(e))

print("=" * 50)


def getServiceInfo():
try:
print('[+] 获取主机正在运行的服务......')
result = subprocess.Popen('net start | find /v "已经启动以下 Windows 服务" | find /v "命令成功完成"', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, err = result.communicate()
netstat_output = out.decode('gbk')
# 去空行
netstat_output = "\n".join(line for line in netstat_output.splitlines() if line.strip())
print(netstat_output)
except subprocess.CalledProcessError as e:
print("[-] 错误: {}".format(e))
print("=" * 50)

bat_file_path = r'getosinfo1.bat'
def getSystemInfo():

# 正常 可在 win2003 cmd下 运行 cmd /c 1.bat 获取相关信息
# 但是在这运行不了 是因为 bat脚本为utf-8编码 需要改成ANSI
# print("[+] 准备运行bat脚本获取系统信息...")

# 这样解决了 输出结果的中文乱码问题 但是在命令行操作时 通过findstr 去筛选中文 编码改变后将会找不到
# subprocess.call(["chcp", "65001"], shell=True)
# result = subprocess.call([bat_file_path], shell=True)

# 调用bat脚本并获取输出
process = subprocess.Popen([bat_file_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
output, error = process.communicate()

# 输出脚本执行结果
print(output.decode('cp936'))
# print("[+] 运行结束...")

def getScheduleTaskInfo():
pass

def getOSRelease():
print('[+] 检测到当前主机系统为',platform.system() +" "+platform.release())
print('[+] 开始对本机进行信息收集,请稍等片刻......')

if __name__ == "__main__":
getOSRelease()
# 系统信息 通过掉bat脚本获取信息 补丁详情处有点问题!
getSystemInfo()

#自启动项 端口 安装应用 运行服务
getAutoRunInfo()
getPortInfo()
getInstallAppInfo()
getServiceInfo()

# 普通用户没权限 这个可以考虑忽略掉
# getScheduleTaskInfo()


getosinfo1.bat

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
@echo off

echo [+] 系统信息:
systeminfo | findstr /i /c:"主机名" /c:"OS 名称" /c:"OS 版本" | find /v "BIOS 版本"

echo [+] IPv4地址:
for /f "tokens=2 delims=:" %%a in ('ipconfig ^| findstr /i "IPv4 地址 IP Address" ^| findstr /i /v "IPv6"') do (
echo %%a
)
endlocal

echo [+] 列出已安装的修复补丁:
setlocal enabledelayedexpansion

REM 运行 systeminfo 命令并将结果保存到临时文件
systeminfo > systeminfo_output.txt

REM 遍历文件内容

for /f "tokens=* delims= " %%a in ('type systeminfo_output.txt') do (
echo %%a | findstr /r /C:"\[[0-9]*\]\:\ KB[0-9][0-9][0-9][0-9][0-9][0-9][0-9]"
echo %%a | findstr /r /C:"\[[0-9]*\]\:\ Q[0-9][0-9][0-9][0-9][0-9][0-9]"
)

REM 删除临时文件
del systeminfo_output.txt

endlocal


Version3

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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# -*- coding: utf-8 -*-
import platform
import winreg
import re
import subprocess

service_port_mapping = {
21: "FTP/TFTP/VSFTPD (File Transfer Protocol)",
22: "SSH (Secure Shell)",
23: "Telnet (Remote Connection)",
25: "SMTP (Email)",
53: "DNS (Domain Name System)",
67: "DHCP (Dynamic Host Configuration Protocol)",
68: "DHCP (Dynamic Host Configuration Protocol)",
110: "POP3 (Email)",
123: "NTP",
135: "RPC(Remote Procedure Call)",
137: "Samba (File Sharing)",
139: "Samba (File Sharing)",
143: "IMAP (Email)",
161: "SNMP (Simple Network Management Protocol)",
389: "LDAP (Lightweight Directory Access Protocol)",
445: "SMB (Server Message Block)",
512: "Linux Rexec (Remote Execution Service)",
513: "Linux Rexec (Remote Execution Service)",
514: "Linux Rexec (Remote Execution Service)",
873: "Rsync (Remote File Synchronization)",
1080: "Socket",
1098: "JAVARMI",
1352: "Lotus Domino (Email)",
1433: "MSSQL (Microsoft SQL Server)",
1521: "Oracle Database",
2049: "NFS (Network File System)",
2181: "Zookeeper",
2222: "DA",
2375: "Docker Remote API",
2601: "zebra",
3306: "MySQL Database",
3128: "squid",
3389: "RDP (Remote Desktop Protocol)",
4100: "SysBase",
4440: "rundeck",
4848: "GlassFish Console",
5000: "Sybase/DB2 Database",
5422: "PostgreSQL Database",
5432: "PostgreSQL Database",
5632: "PCAnywhere Service",
5900: "VNC (Virtual Network Computing)",
5984: "CouchDB",
6082: "Varnish",
6379: "Redis Database",
7001: "WebLogic",
7002: "WebLogic",
80: "HTTP",
443: "HTTPS",
8000: "Jdwp",
8069: "Zabbix",
8161: "ActiveMQ",
8080: "Jboss/Tomcat/Resin/GlassFish/Jenkins/Jetty",
8089: "Jboss/Tomcat/Resin/GlassFish/Jenkins/Jetty",
8083: "InfluxDB",
8086: "InfluxDB",
8980: "OpenNMS",
9000: "FastCGI",
9080: "Websphere Console",
9090: "Websphere Console",
9200: "Elasticsearch",
9300: "Elasticsearch",
11211: "Memcached",
27017: "MongoDB",
27018: "MongoDB",
50000: "SAP",
50010: "Hadoop",
50030: "Hadoop",
50070: "Hadoop",

}

def get_startup_items(hive, subkey):
try:
key = winreg.OpenKey(hive, subkey, 0, winreg.KEY_READ)

startup_items = {}
index = 0

while True:
try:
name, value, _ = winreg.EnumValue(key, index)
startup_items[name] = value
index += 1
except OSError:
# 到达注册表末尾
break

return startup_items

except Exception as e:
# print("[-] Error: {}".format(e))
return {}

# 读取 HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
startup_items_current_user_run = get_startup_items(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run")
# 读取 HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
startup_items_current_user_runonce = get_startup_items(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce")
# 读取 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
startup_items_local_machine_run = get_startup_items(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run")
# 读取 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
startup_items_local_machine_runonce = get_startup_items(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce")

def print_startup_items(startup_items, title):
if startup_items:
print("[+] {}: ".format(title))
for name, value in startup_items.items():
print(name)
# print("Name: {}".format(name))
# print("Path: {}".format(value))
# print("-"*50)
else:
# print("{} is empty.\n".format(title))
pass

def list_registry_subkeys(hive, subkey):
try:
with winreg.OpenKey(hive, subkey) as key:
subkeys_count, _, _ = winreg.QueryInfoKey(key)
subkeys = [winreg.EnumKey(key, i) for i in range(subkeys_count)]
return subkeys
except Exception as e:
# print("[-] Error: {}".format(e))
return []

def get_registry_value(hive, subkey, value_name):
try:
with winreg.OpenKey(hive, subkey) as key:
value, _ = winreg.QueryValueEx(key, value_name)
return value
except Exception as e:
# print("[-] Error: {}".format(e))
return None

def getInstallAppInfo():
print("[+] 获取主机已安装应用信息......")
# 列出 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall 下的子项及其 DisplayName 值
hive1 = winreg.HKEY_LOCAL_MACHINE
subkey = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
subkeys1 = list_registry_subkeys(hive1, subkey)

hive2 = winreg.HKEY_CURRENT_USER
subkeys2 = list_registry_subkeys(hive2, subkey)
if subkeys1:
print("[+] HKLM:")

# 打印结果
for subkey_name in subkeys1:
subkey_path = r"{}\{}".format(subkey, subkey_name)
display_name = get_registry_value(hive1, subkey_path, "DisplayName")

if display_name:
print("{}".format(display_name))
else:
pass

# print("-" * 50)
if subkeys2:
print("[+] HKCU:")

for subkey_name in subkeys2:
subkey_path = r"{}\{}".format(subkey, subkey_name)
display_name = get_registry_value(hive2, subkey_path, "DisplayName")

if display_name:
print("{}".format(display_name))
else:
pass

print("=" * 50)

def getAutoRunInfo():
print("[+] 获取主机启动项信息......")
print_startup_items(startup_items_current_user_run, "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run")
print_startup_items(startup_items_current_user_runonce, "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce")
print_startup_items(startup_items_local_machine_run, "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run")
print_startup_items(startup_items_local_machine_runonce, "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce")
print("=" * 50)

def getPortInfo():
print("[+] 获取主机开放端口服务信息......")
services_found = [] # 保存识别出的端口服务信息
services_unfound = []
try:
result = subprocess.Popen(["netstat", "-ano"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, err = result.communicate()
netstat_output = out.decode('gbk')
# print(netstat_output)

# 使用正则表达式匹配并提取信息
for line in netstat_output.splitlines():
match = re.match(r'\s*TCP\s+(\S+)\s+(\S+)\s+(\S+)\s+(\d+)', line)
if match:
local_address, _, state, pid = match.groups()

# 只输出 LISTENING 状态的信息,并且只显示本地地址、状态和 PID
if state in ["LISTENING", "ESTABLISHED"]:
# 从 local_address 中提取 IP 地址和端口
ip_port_match = re.match(r'(\S+):(\d+)', local_address)
if ip_port_match:
ip, port = ip_port_match.groups()
# 尝试从字典中获取服务信息,如果没有找到则输出 "Unknown Service"
service = service_port_mapping.get(int(port), "Unknown Service")
# 输出 IP地址、端口、状态和 PID、服务
if service != "Unknown Service":
services_found.append({"port": port, "service": service})
else:
services_unfound.append({"port": port, "service": service})

# 本地连接IP 端口去重 并用port进行排序
services_found = [dict(t) for t in {tuple(d.items()) for d in services_found}]
services_found = sorted(services_found, key=lambda x: int(x['port']))

services_unfound = [dict(t) for t in {tuple(d.items()) for d in services_unfound}]
services_unfound = sorted(services_unfound, key=lambda x: int(x['port']))

print("[+] 共匹配到 {} 个已知端口服务".format(len(services_found)))
print("[+] 共匹配到 {} 个未知端口服务".format(len(services_unfound)))

print("[+] 识别出的端口服务:")
if services_found:
for service_info in services_found:
print(" {}\t\t{}".format(service_info['port'], service_info['service']))

print("[+] 未识别出的端口服务:")
if services_unfound:
for service_info in services_unfound:
print(" {}\t\t{}".format(service_info['port'], service_info['service']))

# 如果未找到相关信息,则输出一条消息
if not any(re.match(r'\s*TCP\s+(\S+)\s+(\S+)\s+(\S+)\s+(\d+)', line) for line in netstat_output.splitlines()):
print("[-] 未找到相关信息!")

except subprocess.CalledProcessError as e:
print("[-] 错误: {}".format(e))

print("=" * 50)


def getServiceInfo():
try:
print('[+] 获取主机正在运行的服务......')
result = subprocess.Popen('net start | find /v "已经启动以下 Windows 服务" | find /v "命令成功完成"', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, err = result.communicate()
netstat_output = out.decode('gbk')
# 去空行
netstat_output = "\n".join(line for line in netstat_output.splitlines() if line.strip())
print(netstat_output)
except subprocess.CalledProcessError as e:
print("[-] 错误: {}".format(e))
print("=" * 50)



def getSystemInfo():
cmd_command1 = r'systeminfo | findstr /i /c:"主机名" /c:"OS 名称" /c:"OS 版本" | find /v "BIOS 版本"'
process = subprocess.Popen(cmd_command1, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout1, stderr1 = process.communicate()

print(stdout1.decode('gbk'))
if stderr1:
print("[-] error:", stderr1.decode('gbk'))

cmd_command2 = r'cmd /c ipconfig | findstr /i "IPv4 地址 IP Address" | findstr /i /v "IPv6"'

process = subprocess.Popen(cmd_command2, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

stdout2, stderr2 = process.communicate()
if stderr2:
print("[-] error:", stderr2.decode('gbk'))

# 使用正则表达式匹配IPv4地址
ipv4_pattern1 = re.compile(r'IPv4 地址[^:]+:\s*([\d.]+)', re.IGNORECASE)
ipv4_pattern2 = re.compile(r'IP Address\. .+? : (\d+\.\d+\.\d+\.\d+)', re.IGNORECASE)

match1 = ipv4_pattern1.search(stdout2.decode('gbk', errors='replace'))
match2 = ipv4_pattern2.search(stdout2.decode('gbk', errors='replace'))

if match1:
ipv4_address = match1.group(1)
print("IPv4地址:\t\t", ipv4_address)
elif match2:
ipv4_address = match2.group(1)
print("IPv4地址:\t\t", ipv4_address)

else:
print("[-] 未找到IPv4地址")

cmd_command3 = 'systeminfo'
process = subprocess.Popen(cmd_command3, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stdout3, stderr3 = process.communicate()
if stderr3:
print("[-] error:", stderr3.decode('gbk'))

kb_pattern = re.compile(r'KB\d{7}')
q_pattern = re.compile(r'Q\d{6}')

matches_kb = kb_pattern.findall(stdout3.decode('gbk'))
matches_q = q_pattern.findall(stdout3.decode('gbk'))

if matches_kb:
print("已安装" + str(len(matches_kb)) + "个补丁:\t", matches_kb)
if matches_q:
print("已安装" + str(len(matches_q)) + "个补丁:\t", matches_q)

# 获取返回码
return_code = process.returncode
if return_code != 0:
print("[-] Return Code:", return_code)


def getScheduleTaskInfo():
pass

def getOSRelease():
print('[+] 检测到当前主机系统为',platform.system() +" "+platform.release())
print('[+] 开始对本机进行信息收集,请稍等片刻......')

if __name__ == "__main__":
getOSRelease()
getSystemInfo()
#自启动项 端口 安装应用 运行服务
getAutoRunInfo()
getPortInfo()
getInstallAppInfo()
getServiceInfo()

# 普通用户没权限 这个可以考虑忽略掉
# getScheduleTaskInfo()


Version4

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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
# -*- coding: utf-8 -*-
import platform
import winreg
import re
import subprocess
import os

service_port_mapping = {
21: "FTP/TFTP/VSFTPD (File Transfer Protocol)",
22: "SSH (Secure Shell)",
23: "Telnet (Remote Connection)",
25: "SMTP (Email)",
53: "DNS (Domain Name System)",
67: "DHCP (Dynamic Host Configuration Protocol)",
68: "DHCP (Dynamic Host Configuration Protocol)",
110: "POP3 (Email)",
123: "NTP",
135: "RPC(Remote Procedure Call)",
137: "NetBIOS Name Service(NBNS)",
138: "NetBIOS Datagram Service",
139: "Samba (File Sharing)",
143: "IMAP (Email)",
161: "SNMP (Simple Network Management Protocol)",
389: "LDAP (Lightweight Directory Access Protocol)",
445: "SMB (Server Message Block)",
512: "Linux Rexec (Remote Execution Service)",
513: "Linux Rexec (Remote Execution Service)",
514: "Linux Rexec (Remote Execution Service)",
873: "Rsync (Remote File Synchronization)",
1080: "Socket",
1098: "JAVARMI",
1352: "Lotus Domino (Email)",
1433: "MSSQL (Microsoft SQL Server)",
1521: "Oracle Database",
2049: "NFS (Network File System)",
2181: "Zookeeper",
2222: "DA",
2375: "Docker Remote API",
2601: "zebra",
3306: "MySQL Database",
3128: "squid",
3389: "RDP (Remote Desktop Protocol)",
4100: "SysBase",
4440: "rundeck",
4848: "GlassFish Console",
5000: "Sybase/DB2 Database",
5422: "PostgreSQL Database",
5432: "PostgreSQL Database",
5632: "PCAnywhere Service",
5900: "VNC (Virtual Network Computing)",
5984: "CouchDB",
6082: "Varnish",
6379: "Redis Database",
7001: "WebLogic",
7002: "WebLogic",
80: "HTTP",
443: "HTTPS",
8000: "Jdwp",
8069: "Zabbix",
8161: "ActiveMQ",
8080: "Jboss/Tomcat/Resin/GlassFish/Jenkins/Jetty",
8089: "Jboss/Tomcat/Resin/GlassFish/Jenkins/Jetty",
8083: "InfluxDB",
8086: "InfluxDB",
8980: "OpenNMS",
9000: "FastCGI",
9080: "Websphere Console",
9090: "Websphere Console",
9200: "Elasticsearch",
9300: "Elasticsearch",
11211: "Memcached",
27017: "MongoDB",
27018: "MongoDB",
50000: "SAP",
50010: "Hadoop",
50030: "Hadoop",
50070: "Hadoop",

}

def get_startup_items(hive, subkey):
try:
key = winreg.OpenKey(hive, subkey, 0, winreg.KEY_READ)

startup_items = {}
index = 0

while True:
try:
name, value, _ = winreg.EnumValue(key, index)
startup_items[name] = value
index += 1
except OSError:
# 到达注册表末尾
break

return startup_items

except Exception as e:
# print("[-] Error: {}".format(e))
return {}

# 读取 HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
startup_items_current_user_run = get_startup_items(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run")
# 读取 HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
startup_items_current_user_runonce = get_startup_items(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce")
# 读取 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
startup_items_local_machine_run = get_startup_items(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run")
# 读取 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
startup_items_local_machine_runonce = get_startup_items(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce")

def print_startup_items(startup_items, title):
if startup_items:
print("[+] {}: ".format(title))
for name, value in startup_items.items():
print(name)
# print("Name: {}".format(name))
# print("Path: {}".format(value))
# print("-"*50)
else:
# print("{} is empty.\n".format(title))
pass

def list_registry_subkeys(hive, subkey):
try:
with winreg.OpenKey(hive, subkey) as key:
subkeys_count, _, _ = winreg.QueryInfoKey(key)
subkeys = [winreg.EnumKey(key, i) for i in range(subkeys_count)]
return subkeys
except Exception as e:
# print("[-] Error: {}".format(e))
return []

def get_registry_value(hive, subkey, value_name):
try:
with winreg.OpenKey(hive, subkey) as key:
value, _ = winreg.QueryValueEx(key, value_name)
return value
except Exception as e:
# print("[-] Error: {}".format(e))
return None

def getInstallAppInfo():
print("========================= 安装应用 =========================")
# 列出 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall 下的子项及其 DisplayName 值
hive1 = winreg.HKEY_LOCAL_MACHINE
subkey = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
subkeys1 = list_registry_subkeys(hive1, subkey)

hive2 = winreg.HKEY_CURRENT_USER
subkeys2 = list_registry_subkeys(hive2, subkey)
if subkeys1:
print("[+] HKLM:")

# 打印结果
for subkey_name in subkeys1:
subkey_path = r"{}\{}".format(subkey, subkey_name)
display_name = get_registry_value(hive1, subkey_path, "DisplayName")

if display_name:
print("{}".format(display_name))
else:
pass

if subkeys2:
print("[+] HKCU:")

for subkey_name in subkeys2:
subkey_path = r"{}\{}".format(subkey, subkey_name)
display_name = get_registry_value(hive2, subkey_path, "DisplayName")

if display_name:
print("{}".format(display_name))
else:
pass


def getAutoRunInfo():
print("========================= 自启动项 =========================")
print_startup_items(startup_items_current_user_run, "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run")
print_startup_items(startup_items_current_user_runonce, "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce")
print_startup_items(startup_items_local_machine_run, "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run")
print_startup_items(startup_items_local_machine_runonce, "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce")


def getPortInfo():
print("========================= 开放端口 =========================")
services_TCP_found = [] # 保存识别出的端口服务信息
services_TCP_unfound = []
services_UDP_found = []
services_UDP_unfound = []
try:
result = subprocess.Popen(["netstat", "-ano"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, err = result.communicate()
netstat_output = out.decode('gbk')
# print(netstat_output)

# 使用正则表达式匹配并提取信息
for line in netstat_output.splitlines():
match = re.match(r'\s*TCP\s+(\S+)\s+(\S+)\s+(\S+)\s+(\d+)', line)
if match:
local_address, _, state, pid = match.groups()

# 只输出 LISTENING 状态的信息,并且只显示本地地址、状态和 PID
if state in ["LISTENING", "ESTABLISHED"]:
# 从 local_address 中提取 IP 地址和端口
ip_port_match = re.match(r'(\S+):(\d+)', local_address)
if ip_port_match:
ip, port = ip_port_match.groups()
# 尝试从字典中获取服务信息,如果没有找到则输出 "Unknown Service"
service = service_port_mapping.get(int(port), "Unknown Service")
# 输出 IP地址、端口、状态和 PID、服务
if service != "Unknown Service":
services_TCP_found.append({"port": port, "service": service})
# services_TCP_found.append({"port": port, "pid":pid,"service": service})

else:
services_TCP_unfound.append({"port": port, "service": service})
# services_TCP_unfound.append({"port": port, "pid":pid, "service": service})


# 本地连接IP 端口去重 并用port进行排序
services_TCP_found = [dict(t) for t in {tuple(d.items()) for d in services_TCP_found}]
services_TCP_found = sorted(services_TCP_found, key=lambda x: int(x['port']))

services_TCP_unfound = [dict(t) for t in {tuple(d.items()) for d in services_TCP_unfound}]
services_TCP_unfound = sorted(services_TCP_unfound, key=lambda x: int(x['port']))

print("[+] 共匹配到 {} 个已知TCP端口服务".format(len(services_TCP_found)))
print("[+] 共匹配到 {} 个未知TCP端口服务".format(len(services_TCP_unfound)))

print("[+] 识别出的TCP端口服务:")
if services_TCP_found:
for service_info in services_TCP_found:
print("TCP\t\t{}\t\t{}".format(service_info['port'] ,service_info['service']))
# print("TCP\t\t{}\t\t{}/{}".format(service_info['port'], service_info['pid'],service_info['service']))


print("[+] 未识别出的TCP端口服务:")
if services_TCP_unfound:
for service_info in services_TCP_unfound:
print("TCP\t\t{}\t\t{}".format(service_info['port'], service_info['service']))
# print("TCP\t\t{}\t\t{}/{}".format(service_info['port'], service_info['pid'],service_info['service']))

# 如果未找到相关信息,则输出一条消息
if not any(re.match(r'\s*TCP\s+(\S+)\s+(\S+)\s+(\S+)\s+(\d+)', line) for line in netstat_output.splitlines()):
print("[-] 未找到相关TCP端口服务!")


for line in netstat_output.splitlines():
UDPpattern = re.compile(r'UDP\s+(?P<ip_address>[\w\.\[\]:]+):(?P<port>\d+)\s+\*:\*\s+(?P<pid>\d+)')
UDPmatches = UDPpattern.findall(line)

for UDPmatch in UDPmatches:
service = service_port_mapping.get(int(UDPmatch[1]), "Unknown Service")
# print("UDP:", UDPmatch[0], "Port:", UDPmatch[1], "PID:", UDPmatch[2])
if service != "Unknown Service":
services_UDP_found.append({"port": UDPmatch[1], "service": service})
else:
services_UDP_unfound.append({"port": UDPmatch[1], "service": service})

services_UDP_found = [dict(t) for t in {tuple(d.items()) for d in services_UDP_found}]
services_UDP_found = sorted(services_UDP_found, key=lambda x: int(x['port']))

services_UDP_unfound = [dict(t) for t in {tuple(d.items()) for d in services_UDP_unfound}]
services_UDP_unfound = sorted(services_UDP_unfound, key=lambda x: int(x['port']))

print("[+] 共匹配到 {} 个已知UDP端口服务".format(len(services_UDP_found)))
print("[+] 共匹配到 {} 个未知UDP端口服务".format(len(services_UDP_unfound)))

print("[+] 识别出的UDP端口服务:")
if services_UDP_found:
for service_info in services_UDP_found:
print("UDP\t\t{}\t\t{}".format(service_info['port'], service_info['service']))

print("[+] 未识别出的UDP端口服务:")
if services_UDP_unfound:
for service_info in services_UDP_unfound:
print("UDP\t\t{}\t\t{}".format(service_info['port'], service_info['service']))

except subprocess.CalledProcessError as e:
print("[-] 错误: {}".format(e))



def getServiceInfo():
try:
print('========================= 运行服务 =========================')
result = subprocess.Popen('net start | find /v "已经启动以下 Windows 服务" | find /v "命令成功完成"', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, err = result.communicate()
netstat_output = out.decode('gbk')
# 去空行
netstat_output = "\n".join(line for line in netstat_output.splitlines() if line.strip())
# print(netstat_output)
# 去掉每行前面的几个空格
cleaned_text = "\n".join(line.lstrip() for line in netstat_output.splitlines())
print(cleaned_text)

except subprocess.CalledProcessError as e:
print("[-] 错误: {}".format(e))


def getSystemInfo():
print("========================= 系统信息 =========================")
cmd_command1 = r'systeminfo | findstr /i /c:"主机名" /c:"OS 名称" /c:"OS 版本" | find /v "BIOS 版本"'
process = subprocess.Popen(cmd_command1, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout1, stderr1 = process.communicate()
stdout1 = stdout1.decode('gbk')
stdout1 = "\n".join(line for line in stdout1.splitlines() if line.strip())

print(stdout1)
if stderr1:
print("[-] error:", stderr1.decode('gbk'))

cmd_command2 = r'cmd /c ipconfig | findstr /i "IPv4 地址 IP Address" | findstr /i /v "IPv6"'

process = subprocess.Popen(cmd_command2, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

stdout2, stderr2 = process.communicate()
if stderr2:
print("[-] error:", stderr2.decode('gbk'))

# 使用正则表达式匹配IPv4地址
ipv4_pattern1 = re.compile(r'IPv4 地址[^:]+:\s*([\d.]+)', re.IGNORECASE)
ipv4_pattern2 = re.compile(r'IP Address\. .+? : (\d+\.\d+\.\d+\.\d+)', re.IGNORECASE)

match1 = ipv4_pattern1.search(stdout2.decode('gbk', errors='replace'))
match2 = ipv4_pattern2.search(stdout2.decode('gbk', errors='replace'))

if match1:
ipv4_address = match1.group(1)
print("IPv4地址:\t ", ipv4_address)
elif match2:
ipv4_address = match2.group(1)
print("IPv4地址:\t ", ipv4_address)

else:
print("[-] 未找到IPv4地址")

cmd_command3 = 'systeminfo'
process = subprocess.Popen(cmd_command3, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stdout3, stderr3 = process.communicate()
if stderr3:
print("[-] error:", stderr3.decode('gbk'))

kb_pattern = re.compile(r'KB\d{7}')
q_pattern = re.compile(r'Q\d{6}')

matches_kb = kb_pattern.findall(stdout3.decode('gbk'))
matches_q = q_pattern.findall(stdout3.decode('gbk'))

if matches_kb:
print("已安装" + str(len(matches_kb)) + "个补丁:\t", matches_kb)
if matches_q:
print("已安装" + str(len(matches_q)) + "个补丁:\t", matches_q)

# 获取返回码
return_code = process.returncode
if return_code != 0:
print("[-] Return Code:", return_code)



def getScheduleTaskInfo():
# 指定目录路径
directory = r'C:\Windows\System32\Tasks'
print("========================= 计划任务 =========================")

try:
# 获取目录下的文件列表
file_list = os.listdir(directory)
if file_list:
# 初始化一个空数组用于存储文件名
files_array = []
# 遍历目录下的内容
for filename in file_list:
file_path = os.path.join(directory, filename)
# 检查当前项目是否为文件
if os.path.isfile(file_path):
# 如果是文件,则将其名称添加到数组中
files_array.append(filename)
# 打印存储在数组中的文件名
if files_array:
for file in files_array:
print("{}".format(file))
else:
print("[-] 未找到计划任务!")


except FileNotFoundError:
# 处理找不到目录的情况
# print("[-] 目录 '{}' 不存在".format(directory))
print("[-] 未找到计划任务!")

def getOSRelease():
print('[+] 开始对本机进行信息收集,请稍等片刻......')
print('[+] 检测到当前主机系统为',platform.system() +" "+platform.release())


if __name__ == "__main__":
getOSRelease()
getSystemInfo()
getAutoRunInfo()
getPortInfo()
getInstallAppInfo()
getServiceInfo()
getScheduleTaskInfo()


欢迎关注我的其它发布渠道

------------- 💖 🌞 本 文 结 束 😚 感 谢 您 的 阅 读 🌞 💖 -------------