【问题标题】:Get reboot history with python in Windows在 Windows 中使用 python 获取重启历史
【发布时间】:2020-11-06 07:28:18
【问题描述】:

我试图使用 python 从 Windows 10 计算机获取重启历史记录,但我担心我无法读取事件查看器。

是否有任何选项可以获得类似于此 powershell 行的内容?

get-eventlog system | where-object {$_.eventid -eq 1074} | select Timegenerated, EntryType, Message

主要思想是对本地网络中的计算机列表进行此“查询”。

【问题讨论】:

  • 可以从 Python 调用 PowerShell 的 CLI:Windows PowerShell:powershell.exe; PowerShell [核心] v6+:pwsh.exe.
  • 你可能想看看这个 >>> python - 读取特定的 Windows 事件日志事件 - 堆栈溢出 — stackoverflow.com/questions/11219213/…
  • @mklement0 您必须使用 pythons subprocess 模块在 python 中运行 powershell。使用像 pywin32 这样与本机 COM 对象交互的 python 库可能更安全。
  • @RoadRunner:是的,但这与您调用的 PowerShell 命令本身一样安全或不安全。这种方法的优点是您可以按原样重用现有的 PowerShell 命令。缺点是性能(尽管在这样一个长时间运行的进程的情况下可能无关紧要)和需要解析 PowerShell 命令的 text 输出(尽管可以想象,你可以通过-of XML输出CLIXML并在Python中解析XML)。

标签: python powershell reboot


【解决方案1】:

最简单的方法是从 Python 调用 PowerShell 的 CLI:Windows PowerShell:powershell.exe; PowerShell [核心] 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 命令输出。可以想象,您可以传递-of XML 以使PowerShell 输出CLIXML 并在Python 中解析XML);更简单的选择是修改 Powershell 命令以返回更结构化的输出,例如将| ConvertTo-Csv
      | ConvertTo-Json 附加到命令中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 2011-01-16
    相关资源
    最近更新 更多