本文目录导读:

用脚本高效获取Windows与Linux安全配置
目录导读
- 为什么需要自动化获取系统保护状态? —— 运维痛点与效率提升
- Windows系统保护状态脚本实战 —— PowerShell与WMIC双方案
- Linux系统保护状态脚本实战 —— Bash与systemd-analyze联动
- 跨平台脚本整合技巧 —— 远程采集与日志统一输出
- 常见问答 —— 权限、报错与自动化调度
为什么需要自动化获取系统保护状态?
在服务器运维、安全审计或日常巡检中,系统保护状态是一个关键指标,它涵盖防火墙启用状况、安全策略生效状态、关键服务运行检测(如Windows Defender、Linux的auditd)、系统更新状态等,手动逐台检查不仅耗时,而且容易遗漏,通过脚本批量获取,能提升效率并保证一致性。
核心需求场景:
- 安全合规检查(如等保2.0要求定期检查防火墙规则)
- 大规模服务器巡检(60+台Linux服务器)
- 自动化告警:当保护机制失效时主动通知
Windows系统保护状态脚本实战
1 使用PowerShell获取核心保护状态
PowerShell是Windows下获取系统状态的利器,以下脚本将检查:Windows Defender状态、防火墙规则、用户账户控制(UAC) 和BitLocker加密状态。
# 获取Windows Defender实时保护状态
$defenderStatus = Get-MpComputerStatus | Select-Object -Property RealTimeProtectionEnabled
# 获取防火墙是否启用(所有配置文件)
$firewallStatus = Get-NetFirewallProfile | Select-Object -Property Name, Enabled
# 检查UAC级别
$uacLevel = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name "ConsentPromptBehaviorAdmin"
# 输出结果(可定向至CSV文件)
$protectionReport = [PSCustomObject]@{
ComputerName = $env:COMPUTERNAME
DefenderRealTime = $defenderStatus.RealTimeProtectionEnabled
FirewallProfiles = ($firewallStatus | ForEach-Object {"$($_.Name):$($_.Enabled)"}) -join "; "
UACLevel = $uacLevel.ConsentPromptBehaviorAdmin
}
$protectionReport | Export-Csv -Path "C:\Reports\ProtectionStatus.csv" -Append -NoTypeInformation
脚本执行说明:
- 需以管理员权限运行PowerShell,否则防火墙状态可能受限。
- 输出结果保存在本地CSV文件,便于后续汇总。
2 使用WMIC(旧系统兼容)
对于Windows 7/Server 2008等老系统,可用WMIC:
WMIC /NAMESPACE:\\root\SecurityCenter2 PATH AntiVirusProduct GET displayName,productState
productState字段需解析为十六进制:0x2表示已启用实时保护,0x1表示禁用,手动解析不方便,推荐PowerShell方案。
Linux系统保护状态脚本实战
1 Bash脚本检查核心安全组件
Linux系统保护状态通常涉及:SELinux状态、防火墙(iptables/firewalld)、auditd服务、系统更新状态,以下是一段兼容CentOS/Ubuntu的脚本:
#!/bin/bash
# 输出当前系统保护状态
echo "=== System Protection Status ==="
# 1. 检查SELinux
if command -v getenforce &> /dev/null; then
selinux_status=$(getenforce)
echo "SELinux: $selinux_status"
else
echo "SELinux: Not installed"
fi
# 2. 检查防火墙状态(优先firewalld,其次iptables)
if systemctl is-active firewalld &> /dev/null; then
echo "Firewalld: Active"
elif systemctl is-active iptables &> /dev/null; then
echo "iptables: Active"
else
echo "Firewall: Inactive"
fi
# 3. 检查auditd审计服务
if systemctl is-active auditd &> /dev/null; then
echo "auditd: Running"
else
echo "auditd: Stopped"
fi
# 4. 检查未安装的安全更新(Ubuntu/Debian用apt,CentOS用yum)
if command -v apt &> /dev/null; then
updates=$(apt list --upgradable 2>/dev/null | grep -c "security")
echo "Pending security updates: $updates"
elif command -v yum &> /dev/null; then
updates=$(yum check-update --security 2>/dev/null | grep -c "x86_64")
echo "Pending security updates: $updates"
fi
# 输出到日志文件(追加时间戳)
echo "Date: $(date)" >> /var/log/protection_check.log
2 使用systemd-analyze获取安全服务时间线
systemd-analyze blame可查看服务启动耗时,但更关键的systemd-analyze security(需安装systemd-analyze)能输出安全风险评分:
systemd-analyze security --no-legend 2>/dev/null | head -20
该命令列出各单元的安全风险等级(如UNSAFE、HIGH、OK),适合整合进巡检脚本。
跨平台脚本整合技巧
1 远程采集(Windows至Linux)
若需要从一台Windows机器管理多台Linux服务器,可使用PowerShell Core + SSH(需要安装Posh-SSH模块):
# 批量检查Linux保护状态(假设已有hosts.txt)
$hosts = Get-Content "hosts.txt"
$cred = Get-Credential
$results = @()
foreach ($host in $hosts) {
try {
$session = New-SSHSession -ComputerName $host -Credential $cred -AcceptKey:$true
$output = Invoke-SSHCommand -SessionId $session.SessionId -Command "/path/to/check_protection.sh"
$results += [PSCustomObject]@{
Host = $host
Status = $output.Output
}
} catch {
Write-Warning "Failed to connect $host : $_"
} finally {
Remove-SSHSession -SessionId $session.SessionId
}
}
$results | Export-Csv -Path "multi_hosts_protection.csv"
2 日志统一输出格式
推荐使用JSON格式输出,方便后续接入日志聚合系统(如ELK或Splunk),将Windows脚本的$protectionReport改为:
$protectionReport | ConvertTo-Json | Out-File -Path "C:\Reports\protection.json" -Append
Linux脚本则直接用echo构造JSON:
echo "{\"host\":\"$(hostname)\", \"selinux\":\"$selinux_status\", \"firewall\":\"$firewall_status\"}"
常见问答
Q1:脚本执行报错“权限不足”怎么办?
- Windows:必须以管理员身份运行PowerShell,右键点击PowerShell图标,选择“以管理员身份运行”。
- Linux:部分命令(如
systemctl、yum check-update)需要root权限,可通过sudo执行脚本,或在/etc/sudoers中配置特定命令免密。
Q2:如何定时自动执行并发送报告?
- Windows:使用任务计划程序,创建任务,触发器设为“每天”,操作选择“启动程序”,程序填
powershell.exe,参数填脚本路径。 - Linux:crontab,例如每天凌晨2点执行:
0 2 * * * /root/check_protection.sh > /var/log/protection_daily.log 2>&1
Q3:脚本获取的“系统保护状态”是否包含杀毒软件版本?
可以扩展,Windows下使用Get-MpComputerStatus还可获取AntivirusSignatureVersion、AntispywareSignatureVersion,Linux下如需检查ClamAV,可添加:
clamscan --version | head -1
Q4:脚本能否检查数据备份状态?
可以配合Get-WBSummary(Windows Server Backup)或duplicity status(Linux),但备份状态通常独立于核心保护状态,建议拆分为单独的备份检查脚本。
通过以上脚本示例,你可以快速构建出符合自身环境的系统保护状态自动检查工具,关键在于灵活组合PowerShell与Bash命令,并用统一格式输出日志,如需进一步扩展,可加入邮件告警、Webhook通知等,希望这份指南能帮你提升系统安全运维效率。