尝试将 xml 转换为 csv 的代码出现 KeyError

发布于 2025-01-09 18:23:24 字数 2941 浏览 2 评论 0原文

我对 Python 有点陌生,我需要在我的一门课程中使用它。我从 Windows 安全日志中获得了一个 xml 文件,我需要将其转换为 csv 以便在 Excel 中打开它。我不断收到变量 TargetUserNameKeyError,即使我已将其列在字典中。

我的代码:

#!/usr/bin/env python3

from xml.etree import ElementTree as ET
import csv

tree = ET.parse("SecurityLog-rev2.xml")
root = tree.getroot() 

url = root[0].tag[:-len("Event")]
fieldnames = ['EventID', 'TargetUserSid', 'TargetLogonId', 'TargetUserName',
          'LogonType', 'TargetDomainName', 'ProcessName', 'AuthenticationPackageName',
          'WorkstationName', 'IpPort', 'KeyLength', 'SubjectUserName', 
'LogonProcessName',
          'ProcessId', 'TransmittedServices', 'SubjectUserSid', 'IpAddress', 
'SubjectDomainName',
          'SubjectLogonId', 'LmPackageName', 'LogonGuid', 'ServiceSid', 'ServiceName', 
'TicketOptions',
          'TicketEncryptionType', 'Status', 'PrivilegeList', 'TargetServerName', 
'TargetLogonGuid',
          'TargetInfo', 'CertIssuerName', 'CertSerialNumber', 'CertThumbprint', 
'TargetSid', 'PreAuthType',
          'PackageName', 'Workstation', 'OperationType', 'ObjectName', 
'AdditionalInfo2', 'HandleId',
          'Properties', 'ObjectServer', 'AdditionalInfo', 'AccessList', 'AccessMask', 
'ObjectType',
          'DisplayName', 'AllowedToDelegateTo', 'PrimaryGroupId', 'DnsHostName', 
'SidHistory', 'ProfilePath',
          'NewUacValue', 'HomeDirectory', 'UserAccountControl', 'UserWorkstations', 
'OldUacValue',
          'SamAccountName', 'HomePath', 'PasswordLastSet', 'ComputerAccountChange', 
'LogonHours',
          'AccountExpires', 'ScriptPath', 'UserPrincipalName', 'ServicePrincipalNames', 
'UserParameters',
          'FailureReason', 'SubStatus']

with open ('event_log.csv', 'w') as csvfile:
    writecsv = csv.DictWriter(csvfile, fieldnames = fieldnames)
    writecsv.writeheader()

    for event in root:
        system = event.find(url + "System")
        output = {}
        count = 0
        fields = [('EventID','TargetUserName')]
        for tag,att in fields:
            output[tag] = system.find(url + tag).attrib[att]
        
        output['EventID'] = system.find(url + 'EventID')
        if event.find(url + "EventData") != None:
            for data in event.find(url + "EventData"):
                name = data.attrib['Name']
                output[name] = data.text

        writecsv.writerow(output)

显示有错误的代码行是第 35 行(output[tag] = system.find(url + tag).attrib[att])。

错误代码:

= RESTART: C:\Users\Devli\Downloads\School\Senior 2021-2022\Spring 
2022\Cyber 440 [Capstone]\Windows Security Log 
Analysis\Devlin_logfiles-1.py
Traceback (most recent call last):
  File "C:\Users\Devli\Downloads\School\Senior 2021-2022\Spring 
2022\Cyber 440 [Capstone]\Windows Security Log 
Analysis\Devlin_logfiles-1.py", line 35, in <module>
    output[tag] = system.find(url + tag).attrib[att]
KeyError: 'TargetUserName'

I'm somewhat new to Python and I need to use it for one of my classes. I have been given an xml file from a windows security log, and I need to convert it into a csv to open it in excel. I keep getting a KeyError for the variable TargetUserName, even though I have it listed in my dictionary.

My code:

#!/usr/bin/env python3

from xml.etree import ElementTree as ET
import csv

tree = ET.parse("SecurityLog-rev2.xml")
root = tree.getroot() 

url = root[0].tag[:-len("Event")]
fieldnames = ['EventID', 'TargetUserSid', 'TargetLogonId', 'TargetUserName',
          'LogonType', 'TargetDomainName', 'ProcessName', 'AuthenticationPackageName',
          'WorkstationName', 'IpPort', 'KeyLength', 'SubjectUserName', 
'LogonProcessName',
          'ProcessId', 'TransmittedServices', 'SubjectUserSid', 'IpAddress', 
'SubjectDomainName',
          'SubjectLogonId', 'LmPackageName', 'LogonGuid', 'ServiceSid', 'ServiceName', 
'TicketOptions',
          'TicketEncryptionType', 'Status', 'PrivilegeList', 'TargetServerName', 
'TargetLogonGuid',
          'TargetInfo', 'CertIssuerName', 'CertSerialNumber', 'CertThumbprint', 
'TargetSid', 'PreAuthType',
          'PackageName', 'Workstation', 'OperationType', 'ObjectName', 
'AdditionalInfo2', 'HandleId',
          'Properties', 'ObjectServer', 'AdditionalInfo', 'AccessList', 'AccessMask', 
'ObjectType',
          'DisplayName', 'AllowedToDelegateTo', 'PrimaryGroupId', 'DnsHostName', 
'SidHistory', 'ProfilePath',
          'NewUacValue', 'HomeDirectory', 'UserAccountControl', 'UserWorkstations', 
'OldUacValue',
          'SamAccountName', 'HomePath', 'PasswordLastSet', 'ComputerAccountChange', 
'LogonHours',
          'AccountExpires', 'ScriptPath', 'UserPrincipalName', 'ServicePrincipalNames', 
'UserParameters',
          'FailureReason', 'SubStatus']

with open ('event_log.csv', 'w') as csvfile:
    writecsv = csv.DictWriter(csvfile, fieldnames = fieldnames)
    writecsv.writeheader()

    for event in root:
        system = event.find(url + "System")
        output = {}
        count = 0
        fields = [('EventID','TargetUserName')]
        for tag,att in fields:
            output[tag] = system.find(url + tag).attrib[att]
        
        output['EventID'] = system.find(url + 'EventID')
        if event.find(url + "EventData") != None:
            for data in event.find(url + "EventData"):
                name = data.attrib['Name']
                output[name] = data.text

        writecsv.writerow(output)

The line of code that says there is an error is line 35 (output[tag] = system.find(url + tag).attrib[att]).

Error code:

= RESTART: C:\Users\Devli\Downloads\School\Senior 2021-2022\Spring 
2022\Cyber 440 [Capstone]\Windows Security Log 
Analysis\Devlin_logfiles-1.py
Traceback (most recent call last):
  File "C:\Users\Devli\Downloads\School\Senior 2021-2022\Spring 
2022\Cyber 440 [Capstone]\Windows Security Log 
Analysis\Devlin_logfiles-1.py", line 35, in <module>
    output[tag] = system.find(url + tag).attrib[att]
KeyError: 'TargetUserName'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文