我想要通过Python脚本获取Windows server的登录日志,该怎么写呢
时间: 2024-02-21 15:00:49 浏览: 123
你可以使用Python的win32com模块来访问Windows的事件日志。具体步骤如下:
1. 引入win32com模块
```
import win32com.client
```
2. 创建WMI对象
```
wmi = win32com.client.GetObject("winmgmts:{impersonationLevel=impersonate,(Security)}!\\.\root\cimv2")
```
3. 获取事件日志
```
logs = wmi.ExecQuery("SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'Security'")
```
其中,Logfile参数指定了要获取的事件日志名称,这里选择了“Security”。
4. 遍历事件日志
```
for log in logs:
print(log.Message)
```
这里使用了日志对象的Message属性来获取事件日志内容。
完整代码演示:
```
import win32com.client
wmi = win32com.client.GetObject("winmgmts:{impersonationLevel=impersonate,(Security)}!\\.\root\cimv2")
logs = wmi.ExecQuery("SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'Security'")
for log in logs:
print(log.Message)
```
注意:在使用win32com模块前,需要先安装pywin32库。你可以使用pip install pywin32命令来安装。
阅读全文
相关推荐

















