在 Windows 中使用 python 获取重启历史记录
Get reboot history with python in Windows
我试图通过 python 从 Windows 10 台计算机获取重启历史记录,但恐怕我无法读取事件查看器。
是否有任何选项可以获得类似于此 powershell 行的东西?
get-eventlog system | where-object {$_.eventid -eq 1074} | select Timegenerated, EntryType, Message
主要思想是对本地网络中的计算机列表执行此“查询”。
最简单的方法是 从 Python 调用 PowerShell 的 CLI:Windows PowerShell:powershell.exe
; PowerShell [Core] v6+: pwsh.exe
.
以下Python 3.6+解决方案使用powershell.exe
# Python 3.6+
# (Solutions for earlier versions are possible.)
import subprocess
output = subprocess.run([
'powershell.exe',
'-noprofile',
'-executionpolicy',
'-bypass',
'-c',
'get-eventlog system | where-object {$_.eventid -eq 1074} | select Timegenerated, EntryType, Message'
],
capture_output=True)
# CAVEAT: The *system*'s OEM code page is assumed for decoding the
# raw captured stdout output to text.
# Any in-session changes to the active OEM code page via `chcp`
# are NOT recognized; e.g., if you've changed to page 65001 (UTF-8)
# you must use 'utf-8' explicitly.
print(output.stdout.decode('oem'))
优缺点:
这种方法的优点是您可以按原样重用现有的 PowerShell 命令,它提供了 PowerShell 必须提供的所有高级功能。
缺点是:
性能低下,因为启动 PowerShell 进程的开销(尽管在 运行 这样的长进程的情况下可能无关紧要)
需要解析来自 PowerShell 命令的 for-display 命令输出 return。可以想象,您可以传递 -of XML
以使 PowerShell 输出 CLIXML 并在 Python 中解析 XML);一个更简单的选择是将 Powershell 命令修改为 return 更结构化的输出,例如附加 | ConvertTo-Csv
或
| ConvertTo-Json
到命令。
我试图通过 python 从 Windows 10 台计算机获取重启历史记录,但恐怕我无法读取事件查看器。
是否有任何选项可以获得类似于此 powershell 行的东西?
get-eventlog system | where-object {$_.eventid -eq 1074} | select Timegenerated, EntryType, Message
主要思想是对本地网络中的计算机列表执行此“查询”。
最简单的方法是 从 Python 调用 PowerShell 的 CLI:Windows PowerShell:powershell.exe
; PowerShell [Core] v6+: pwsh.exe
.
以下Python 3.6+解决方案使用powershell.exe
# Python 3.6+
# (Solutions for earlier versions are possible.)
import subprocess
output = subprocess.run([
'powershell.exe',
'-noprofile',
'-executionpolicy',
'-bypass',
'-c',
'get-eventlog system | where-object {$_.eventid -eq 1074} | select Timegenerated, EntryType, Message'
],
capture_output=True)
# CAVEAT: The *system*'s OEM code page is assumed for decoding the
# raw captured stdout output to text.
# Any in-session changes to the active OEM code page via `chcp`
# are NOT recognized; e.g., if you've changed to page 65001 (UTF-8)
# you must use 'utf-8' explicitly.
print(output.stdout.decode('oem'))
优缺点:
这种方法的优点是您可以按原样重用现有的 PowerShell 命令,它提供了 PowerShell 必须提供的所有高级功能。
缺点是:
性能低下,因为启动 PowerShell 进程的开销(尽管在 运行 这样的长进程的情况下可能无关紧要)
需要解析来自 PowerShell 命令的 for-display 命令输出 return。可以想象,您可以传递
-of XML
以使 PowerShell 输出 CLIXML 并在 Python 中解析 XML);一个更简单的选择是将 Powershell 命令修改为 return 更结构化的输出,例如附加| ConvertTo-Csv
或
| ConvertTo-Json
到命令。