python - findstr 函数不适用于原始文件
问题描述
我有一个代码来使用 powershell 使用 Get-GPOReport 导出域控制器的策略。但是,我永远不能在这个导出的 HTML 文件上使用 findstr。唯一可行的方法是如果我将 HTML 文件的扩展名更改为 .txt,然后将其中的所有内容复制到另一个新创建的 .txt 文件(例如 test.txt)。
只有这样,findstr 函数才起作用。有谁知道为什么它不适用于原始文件?
import os, subprocess
subprocess.Popen(["powershell","Get-GPOReport -Name 'Default Domain Controllers Policy' -ReportType HTML -Path 'D:\Downloads\Project\GPOReport.html'"],stdout=subprocess.PIPE)
policyCheck = subprocess.check_output([power_shell,"-Command", 'findstr /c:"Minimum password age"', "D:\Downloads\Project\GPOReport.html"]).decode('utf-8')
print(policyCheck)
# However if I copy all the content in D:\Downloads\Project\GPOReport.html to a newly created test.txt file (MANUALLY - I've tried to do it programmatically, findstr wouldn't work too) under the same directory and use:
power_shell = os.path.join(os.environ["SYSTEMROOT"], "System32","WindowsPowerShell", "v1.0", "powershell.exe")
policyCheck = subprocess.check_output([power_shell,"-Command", 'findstr /c:"Minimum password age"', "D:\Downloads\Project\test.txt"]).decode('utf-8')
print(policyCheck)
# Correct Output Will Show
我得到了什么:
subprocess.CalledProcessError: Command '['C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', '-Command', 'findstr /c:"Minimum password age"', 'D:\Downloads\Project\GPOReport.html']' returned non-zero exit status 1.
预期输出:
<tr><td>Minimum password age</td><td>1 days</td></tr>
解决方案
我不是 Python 人,但我认为这可能是编码问题。基于 findstr 与 Unicode 不兼容的事实。正如@iRon 建议Select-String
的那样,尽管您可能必须引用该.Line
属性才能获得您提到的预期输出,但您应该可以做到这一点。否则它将返回匹配对象。
我将把它留给您将其转换为 Python 代码,但Select-String
命令应该类似于:
(Select-String -Path "D:\Downloads\Project\GPOReport.html" -Pattern "Minimum password age" -SimpleMatch).Line
如果有多个匹配项,这将返回一个字符串数组;进行匹配的行。让我知道这是否有帮助。
推荐阅读
- ios - CallKit 音频会话仅在导航到应用程序时启动
- vue.js - 使用 v-if 有条件地加载字段时如何在 Vuejs 中的输入字段上设置焦点
- java - 在形成数据源之前获取数据库密码
- hibernate - Spring Data JPA 自引用实体
- php - 在检查数组键是否存在时尝试在不同的环境中以不同的方式工作
- c# - 缓存属性(get)与延迟初始化以在统一唤醒之前安全地获取组件(移动平台)
- html - 角度如何将组件特定样式注入
html标签?有没有办法将css打包成文件 - jenkins - 通过 Jenkins Pipeline 启动时排除 Doxygen 的模式
- c++ - Qt 如何让绘图从背景中脱颖而出?
- python-3.x - 如何使用 QSqlQuery 创建更新查询