怎么用脚本获取系统策略设置

wen 实用脚本 1

本文目录导读:

怎么用脚本获取系统策略设置

  1. Windows 系统策略获取
  2. Linux/macOS 系统策略
  3. 跨平台 Python 脚本
  4. 使用建议

Windows 系统策略获取

PowerShell(推荐)

# 获取本地组策略设置
Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\System" -Name "EnableSmartScreen"
# 获取安全策略(如密码策略)
secedit /export /cfg C:\temp\security_policy.txt
Get-Content C:\temp\security_policy.txt
# 获取所有组策略设置
gpresult /H C:\temp\gp_report.html
# 获取特定策略(通过注册表路径)
$policies = @{
    "WindowsUpdate" = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate"
    "Edge" = "HKLM:\SOFTWARE\Policies\Microsoft\Edge"
    "Chrome" = "HKLM:\SOFTWARE\Policies\Google\Chrome"
}
foreach ($key in $policies.Keys) {
    if (Test-Path $policies[$key]) {
        Write-Host "=== $key Policies ==="
        Get-ItemProperty -Path $policies[$key]
    }
}

CMD (批处理)

@echo off
REM 导出安全策略
secedit /export /cfg C:\temp\sec_policy.inf
REM 读取注册表策略
reg query "HKLM\SOFTWARE\Policies\Microsoft\Windows\System" /v EnableSmartScreen
REM 获取密码策略
net accounts
REM 显示所有组策略
gpresult /R

VBScript

' Windows 策略查询脚本
Set objShell = CreateObject("WScript.Shell")
' 读取注册表策略
strKeyPath = "HKLM\SOFTWARE\Policies\Microsoft\Windows\System\"
strValueName = "EnableSmartScreen"
On Error Resume Next
strValue = objShell.RegRead(strKeyPath & strValueName)
If Err.Number = 0 Then
    WScript.Echo "SmartScreen 策略: " & strValue
Else
    WScript.Echo "策略未设置或无法读取"
End If

Linux/macOS 系统策略

Bash 脚本

#!/bin/bash
# 获取系统安全策略
echo "=== SELinux 状态 ==="
getenforce 2>/dev/null || sestatus 2>/dev/null || echo "未安装 SELinux"
echo -e "\n=== AppArmor 策略 ==="
sudo aa-status 2>/dev/null || echo "未启用 AppArmor"
echo -e "\n=== 密码策略 ==="
cat /etc/pam.d/common-password 2>/dev/null | grep -v "^#" | grep "pam_unix.so"
grep -E "PASS_MAX_DAYS|PASS_MIN_DAYS|PASS_WARN_AGE" /etc/login.defs
echo -e "\n=== 审计策略 ==="
auditctl -l 2>/dev/null || echo "auditd 未运行"
echo -e "\n=== 防火墙策略 ==="
if command -v ufw &> /dev/null; then
    sudo ufw status verbose
elif command -v iptables &> /dev/null; then
    sudo iptables -L -n -v
elif command -v nft &> /dev/null; then
    sudo nft list ruleset
fi

macOS 特定策略

#!/bin/zsh
# macOS 策略检查
echo "=== 系统完整性保护 (SIP) ==="
csrutil status
echo -e "\n=== 防火墙设置 ==="
/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate
echo -e "\n=== Gatekeeper 策略 ==="
spctl --status
echo -e "\n=== FileVault 加密状态 ==="
fdesetup status
echo -e "\n=== 安全策略 (MDM相关) ==="
sudo profiles -P -o stdout
echo -e "\n=== 隐私策略 (TCC数据库) ==="
sudo sqlite3 /Library/Application\ Support/com.apple.TCC/TCC.db "SELECT * FROM access" 2>/dev/null | head -20

跨平台 Python 脚本

#!/usr/bin/env python3
import sys
import subprocess
import platform
def get_windows_policies():
    """获取Windows策略"""
    import winreg
    policies = {}
    # 常见策略路径
    policy_paths = {
        "Windows Update": r"SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate",
        "Defender": r"SOFTWARE\Policies\Microsoft\Windows Defender",
        "Edge": r"SOFTWARE\Policies\Microsoft\Edge",
    }
    for name, path in policy_paths.items():
        try:
            with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) as key:
                i = 0
                values = {}
                while True:
                    try:
                        vname, vdata, vtype = winreg.EnumValue(key, i)
                        values[vname] = vdata
                        i += 1
                    except WindowsError:
                        break
                policies[name] = values
        except FileNotFoundError:
            policies[name] = "未设置"
    return policies
def get_linux_policies():
    """获取Linux策略"""
    policies = {}
    # SELinux
    try:
        result = subprocess.run(['getenforce'], capture_output=True, text=True)
        policies['SELinux'] = result.stdout.strip()
    except:
        policies['SELinux'] = "未安装"
    # 密码策略
    try:
        with open('/etc/login.defs', 'r') as f:
            for line in f:
                if 'PASS' in line and not line.startswith('#'):
                    policies[line.split()[0]] = line.split()[1]
    except:
        pass
    return policies
def get_macos_policies():
    """获取macOS策略"""
    policies = {}
    # SIP状态
    result = subprocess.run(['csrutil', 'status'], capture_output=True, text=True)
    policies['SIP'] = result.stdout.strip()
    # Gatekeeper
    result = subprocess.run(['spctl', '--status'], capture_output=True, text=True)
    policies['Gatekeeper'] = result.stdout.strip()
    return policies
def main():
    system = platform.system()
    print(f"检测到操作系统: {system}\n")
    if system == "Windows":
        policies = get_windows_policies()
    elif system == "Linux":
        policies = get_linux_policies()
    elif system == "Darwin":
        policies = get_macos_policies()
    else:
        print("不支持的操作系统")
        sys.exit(1)
    for key, value in policies.items():
        print(f"{key}: {value}")
if __name__ == "__main__":
    main()

使用建议

  1. 权限要求:大多数系统策略需要管理员/root权限才能读取
  2. 安全考虑:脚本可能包含敏感信息,注意保护输出结果
  3. 兼容性:不同Windows版本策略路径可能不同,Linux发行版差异更大
  4. 替代方案:对于复杂策略,考虑使用专门的工具:
    • Windows: LGPO.exe, PolicyAnalyzer
    • Linux: aide, lynis, OpenSCAP
    • macOS: system_profiler, defaults 命令

根据具体需求选择合适的脚本方法,如果只是快速查看,可以使用系统自带工具(gpresult、secedit等)配合输出重定向。

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