我是编程新手。我正在使用 powershell 从远程服务器的 Windows 安全事件日志中过滤和返回文本文件中的记录。我正在使用 python 脚本来计算用户名在文本中出现的次数。针对原始文本文件运行时,python 打印并清空字典 {}。但是,如果我复制文本文件的内容并将其粘贴到一个新的文本文件中并针对它运行我的 python 脚本,它会返回正确的计数:{'name1': 2, 'name2': 13, 'name3':1,'name4':1,'name5':2,'name6':2}。文本文件看起来相同,字符位置也相同。可能是什么问题?
电源外壳
Get-WinEvent -LogName "Security" -ComputerName server01 | Where-Object {$_.ID -eq 4663} | where Message -CNotLike "*name1*" | where Message -CNotLike "*name2*" | Format-List -Property * | Out-File "C:\apowershell\winsec\events.txt"
python
fhand = open('events2.txt')
counts = dict()
for line in fhand:
if line.startswith(' Account Name:'):
words = line.split()
words.remove('Account')
words.remove('Name:')
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
print(counts)
日志记录 消息:尝试访问对象。
Subject:
Security ID: S-1-5-21-495698755-754321212-623647154-4521
Account Name: name1
Account Domain: companydomain
Logon ID: 0x8CB9C5024
Object:
Object Server: Security
Object Type: File
Object Name: e:\share\file.txt
Handle ID: 0x439c
Resource Attributes: S:PAI
Process Information:
Process ID: 0x2de8
Process Name: C:\Windows\System32\memshell.exe
Access Request Information:
Accesses: Execute/Traverse
Access Mask: 0x20
请您参考如下方法:
答案在您的问题陈述中。您正在读取一个在 MS Windows 上创建的文件,其中包含一个在(可能)非 Windows 系统上运行的 python 程序。
问题是原始文件的字符编码与您的 Python 程序所期望的不匹配。具体来说,原始文件采用 UCS-2(或 UTF-16)编码。如果你在类似 UNIX 的操作系统上运行你的 python 代码,它可能需要 UTF-8。但这取决于您的语言环境,请查看 locale 的输出。谷歌“python utf-16 decode”以获取有关如何处理此问题的想法。尽管就个人而言,我并没有尝试让您的 Python 程序处理 UTF-16,而是尝试找到一种方法在 Windows 系统上将内容转换为 UTF-8。
