怎么用脚本获取系统安全日志

wen 实用脚本 3

本文目录导读:

怎么用脚本获取系统安全日志

  1. Windows 系统 (PowerShell & CMD)
  2. Linux 系统 (Bash)
  3. Python 脚本 (跨平台)
  4. 关键注意事项
  5. 总结推荐

获取操作系统安全日志需要通过脚本调用系统底层接口或日志管理工具,根据操作系统不同,方法有所差异,以下分别针对 WindowsLinux 提供几种常见脚本实现方案。

Windows 系统 (PowerShell & CMD)

Windows 安全日志通常存储在 Security 日志通道中,普通用户可能权限不足,需要以管理员身份运行脚本。

使用 PowerShell (推荐)

PowerShell 是获取 Windows 日志最强大的脚本工具。

方法 A:使用 Get-WinEvent (最常用)

# 获取最新的 50 条安全日志
Get-WinEvent -LogName Security -MaxEvents 50
# 筛选特定事件ID (4624=登录成功, 4625=登录失败)
Get-WinEvent -LogName Security -MaxEvents 100 | Where-Object { $_.Id -eq 4624 -or $_.Id -eq 4625 } | Format-List
# 导出到 CSV 文件
Get-WinEvent -LogName Security -MaxEvents 1000 | Export-Csv -Path "C:\Temp\SecurityLog.csv" -NoTypeInformation

方法 B:使用 Get-EventLog (旧版,但简单)

# 获取最新的 100 条
Get-EventLog -LogName Security -Newest 100
# 按时间筛选 (最近1小时)
$time = (Get-Date).AddHours(-1)
Get-EventLog -LogName Security -After $time
# 筛选登录失败事件 (EventID 4625)
Get-EventLog -LogName Security | Where-Object { $_.EventID -eq 4625 }

方法 C:使用 WMI/CIM (远程或高级查询)

# 通过 WMI 查询安全日志
Get-CimInstance -ClassName Win32_NTLogEvent -Filter "LogFile='Security'" -Property "TimeGenerated","EventCode","Message" -Max 100

使用 CMD (批处理脚本)

CMD 本身能力有限,通常配合 wevtutil (Windows Event Log Utility) 使用。

@echo off
REM 导出安全日志到 evtx 文件
wevtutil epl Security C:\Temp\SecurityLog.evtx
REM 列出最近 10 条 (但很简陋)
wevtutil qe Security /c:10 /rd:true /f:text
echo 日志已导出到 C:\Temp\SecurityLog.evtx

提示wevtutil 的查询功能较弱,其实用 PowerShell 更好。


Linux 系统 (Bash)

Linux 的安全日志位置取决于发行版和日志系统。

  • 传统syslog:通常位于 /var/log/secure (RedHat/CentOS) 或 /var/log/auth.log (Debian/Ubuntu)。
  • systemd-journald (较新的发行版,如 Ubuntu 16.04+, CentOS 7+):使用 journalctl 命令。

使用 journalctl (推荐)

这是访问 systemd 日志的标准工具,可以精确筛选安全事件。

#!/bin/bash
# 查看最近 50 条安全日志 (内核和认证相关)
sudo journalctl -n 50 -t sshd -t sudo -t login -t gdm-password
# 查看最近 1 小时的认证失败 (sshd)
sudo journalctl -u sshd --since "1 hour ago" | grep "Failed password"
# 查看所有认证失败记录
sudo journalctl -t sshd --since today | grep "authentication failure"
# 查看所有 sudo 执行记录
sudo journalctl -t sudo --since "2023-01-01 00:00:00"

使用 grep 从文本日志中提取 (传统方法)

#!/bin/bash
# 从 /var/log/auth.log 或 /var/log/secure 中提取
LOG_FILE="/var/log/auth.log"   # Debian/Ubuntu
# LOG_FILE="/var/log/secure"   # CentOS/RHEL
# 查看最近 20 条安全相关记录
tail -n 20 $LOG_FILE
# 筛选 SSH 登录失败
grep "Failed password" $LOG_FILE | tail -50
# 筛选 su 切换失败
grep "FAILED SU" $LOG_FILE | tail -20
# 统计今日认证失败次数
grep "$(date +%b\ %e)" $LOG_FILE | grep -c "Failed password"

使用 last 命令 (查看登录历史)

last 命令读取 /var/log/wtmp,可以显示用户登录/注销历史,但不包含详细安全事件。

# 查看所有登录记录
last -n 50
# 查看失败的登录尝试 (读取 /var/log/btmp)
sudo lastb -n 20

Python 脚本 (跨平台)

Python 可以编写跨平台脚本,通过调用系统工具或 API 获取日志。

Windows 示例

import subprocess
import json
def get_windows_security_log(max_events=50):
    """通过 PowerShell 命令获取安全日志"""
    ps_script = f"""
    Get-WinEvent -LogName Security -MaxEvents {max_events} | Select-Object TimeCreated, Id, LevelDisplayName, Message | ConvertTo-Json
    """
    cmd = ["powershell.exe", "-Command", ps_script]
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode != 0:
        print(f"错误: {result.stderr}")
        return []
    try:
        logs = json.loads(result.stdout)
        return logs if isinstance(logs, list) else [logs]
    except json.JSONDecodeError:
        print(f"解析错误: {result.stdout[:200]}")
        return []
# 使用示例
logs = get_windows_security_log(20)
for log in logs:
    print(f"[{log['TimeCreated']}] EventID: {log['Id']} - {log['Message'][:100]}")

Linux 示例

import subprocess
def get_linux_security_log(lines=50):
    """通过 journalctl 获取安全日志"""
    cmd = [
        "sudo", "journalctl",
        "-n", str(lines),
        "-t", "sshd",
        "-t", "sudo",
        "-t", "login",
        "--since", "1 hour ago",
        "--no-pager"
    ]
    result = subprocess.run(cmd, capture_output=True, text=True)
    return result.stdout
# 使用示例
log_output = get_linux_security_log(30)
print(log_output)

关键注意事项

  1. 权限要求

    • Windows:必须以管理员身份运行 PowerShell 或 CMD。
    • Linux:通常需要 root 权限 (如 sudo journalctl 或读取 /var/log/auth.log)。
  2. 事件ID参考 (Windows)

    • 4624:登录成功
    • 4625:登录失败
    • 4634:注销
    • 4648:使用显式凭据登录
    • 4672:分配特殊权限
    • 4720:创建用户
    • 4732:用户添加到本地组
  3. 日志轮转

    • 确保在循环读取日志时,日志文件没有被轮转(系统自动重命名),考虑使用 -ftail -F 追踪活动日志。
  4. 性能

    • 安全日志可能非常大,始终在使用时添加 -MaxEvents-n 限制返回条数,避免系统过载。
  5. 输出格式

    推荐输出为 CSV 或 JSON 以便后续分析。


总结推荐

  • WindowsPowerShell 一行命令 Get-WinEvent -LogName Security -MaxEvents 100
  • LinuxBash + journalctlgrep tailjournalctl -u sshd --since today | grep "Failed password"
  • 跨平台/自动化Python 调用系统命令或库(Windows) / 解析文本(Linux)。

选择哪种方法取决于你的使用场景:快速查看、定期审计还是作为运维自动化脚本的一部分。

抱歉,评论功能暂时关闭!