我想找到一种更快的方法,用字符串kittycat替换每个用户名。
2018 Aug 01 01:59:59 WinEvtLog: Security: AUDIT_FAILURE(4625): Microsoft-Windows-Security-Auditing: peter.parker: no domain: my.own.domain: An account failed to log on.
2018 Aug 02 01:59:59 WinEvtLog: Security: AUDIT_SUCCESS(4624): Microsoft-Windows-Security-Auditing: 4dministr4t0r: my-log: still.my.domain: An account was successfully logged on.
2018 Aug 03 01:59:59 WinEvtLog: Security: AUDIT_FAILURE(4768): Microsoft-Windows-Security-Auditing: (no user): no domain: my.other.domain: A Kerberos authentication ticket (TGT) was requested.
(正则表达式假设-没有用户名包含“:”)
__ My_Current_Solution
import re
regex = '^.+Auditing\:\s+(?P<username>.+?(?=\:))'
result = re.search(regex, string)
username = result.group('username')
result=re.sub(username,kittycat,string)
print result
答案 0 :(得分:1)
您可以使用
import re, hashlib
s = "2018 Aug 01 01:59:59 WinEvtLog: Security: AUDIT_FAILURE(4625): Microsoft-Windows-Security-Auditing: peter.parker: no domain: my.own.domain: An account failed to log on."
print(re.sub(r'(Auditing:\s*)([^:]+)', lambda m: m.group(1) + hashlib.sha512(m.group(2).encode()).hexdigest(), s))
# => 2018 Aug 01 01:59:59 WinEvtLog: Security: AUDIT_FAILURE(4625): Microsoft-Windows-Security-Auditing: 2dd95ce5e79de5cedbb3f50b635b9b9125c19464b15938a242aec0db227cfb408570837b12912db97704cac96d22d9fda9f140ea63adf17959c334570ccc8a41: no domain: my.own.domain: An account failed to log on.
请参见Python demo
模式详细信息
(Auditing:\s*)
-捕获组1:Auditing:
子字符串,然后捕获0+空格([^:]+)
-捕获第2组::
以外的一个或多个字符。在替换lambda表达式中,第1组用m.group(1)
引用,而第2组值用m.group(2)
引用。