windows,linux基线管理

linux

#coding=utf8
import os
import re
import subprocess
import platform
import json

def get_base_line(file_path, pattern_list):
    """
    针对 未用#注释关键字是唯一情况
    :param file_path: 文件路径
    :param pattern_list: 匹配的关键字列表
    :return:
    """
    result_dict = dict()
    if os.path.exists(file_path):
        with open(file_path) as f:
            content = f.read().split("\n")
    else:
        return dict()
    for backend_text in content:
        if backend_text.strip().startswith('#') or not backend_text:
            pass
        else:
            for item in pattern_list:
                result = "".join(re.findall('(?<={item})[\s=\t]{{0,}}[-]{{0,1}}\d+'.
                                            format(item=item), backend_text)).strip().strip("=").strip()
                if result:
                    result_dict[item] = result
    return result_dict


def get_base_line2(file_path, pattern):
    """
    针对 未用#注释关键字不是唯一情况
    :param file_path: 文件路径
    :param pattern: 匹配的关键字
    :return:
    """
    result_list = list()
    if os.path.exists(file_path):
        with open(file_path) as f:
            content = f.read().split("\n")
    else:
        return str()
    for backend_text in content:
        if backend_text.strip().startswith('#') or not backend_text:
            pass
        else:
            result = "".join(re.findall('(?<={item})[\s=\t]{{0,}}.*'.
                                        format(item=pattern), backend_text)).strip().strip("=").strip()
            if result:
                result_list.append(result)
    results = ",".join(result_list)
    return results


def get_serverce_status(server_name, version):
    if version and int(version) == 7:
        server = server_name
        run_status = "active"
        init_status = 'enabled'
        if server_name == "iptables":
            server = "firewalld"
        cmd1 = "systemctl status {server}".format(server=server)
        ret = "".join(re.findall('(?<=Active:)[\s,\t]{0,}\w+',subprocess.
                                        check_output(cmd1, shell=True).decode())).strip()
        if ret == "inactive":
            run_status = "inactive"
        cmd2 = "systemctl list-unit-files |grep {server}".format(server=server)
        ret2 = "".join(re.findall('(?<=firewalld\.service)[\t\s]{0,}\w+',subprocess.
                                         check_output(cmd2, shell=True).decode())).strip()
        if ret2 == "disabled":
            init_status = "disabled"
        return "{run}/{init}".format(run=run_status, init=init_status)
    else:
        run_status = "active"
        init_status = 'enabled'
        cmd1 = "service {server} status".format(server=server_name)
        result = subprocess.Popen(cmd1,shell=True,stdout=subprocess.PIPE).communicate()[0].strip()
        ret1 = re.findall('not running|not operational|is stopped',result)
        if not result or ret1:
            run_status = "inactive"
        cmd2 = "chkconfig|grep {server}".format(server=server_name)
        result2 = subprocess.Popen(cmd2,shell=True,stdout=subprocess.PIPE).communicate()[0]
        ret = re.search('3:(?P<th>\w+).*5:(?P<fi>\w+)',result2)
        if not result2:
            init_status = "disabled"
        else:
            if ret.group('th') == "off" and ret.group('fi') == "off":
                init_status = "disabled"
        return "{run}/{init}".format(run=run_status, init=init_status)


if __name__ == "__main__":
    sys_auth_info = get_base_line("/etc/pam.d/system-auth",
                              ["retry", "minlen", "dcredit", "ucredit", 'ocredit', "lcredit", "remember"])
    login_info = get_base_line("/etc/login.defs", ["PASS_MAX_DAYS", "PASS_MIN_DAYS", "PASS_MIN_LEN", "PASS_WARN_AGE"])
    dns = get_base_line2("/etc/resolv.conf", "nameserver")
    date_cmd = "date +%Z_%z"
    time_zone = subprocess.check_output(date_cmd,shell=True).decode().strip()
    version = "".join(re.findall('(?<=el)\d+',platform.platform()))
    NetworkManager = get_serverce_status("NetworkManager",version)
    iptables = get_serverce_status("iptables",version)
    kdump = get_serverce_status("kdump",version)
    data = {
        "auth_retry": sys_auth_info.get("retry",str()),
        "auth_minlen": sys_auth_info.get("minlen",str()),
        "auth_dcredit": sys_auth_info.get("dcredit", str()),
        "auth_ucredit": sys_auth_info.get("ucredit", str()),
        "auth_ocredit": sys_auth_info.get("ocredit", str()),
        "auth_lcredit": sys_auth_info.get("lcredit", str()),
        "auth_remember": sys_auth_info.get("remember", str()),
        "pass_max_days": login_info.get("PASS_MAX_DAYS",str()),
        "pass_min_days": login_info.get("PASS_MIN_DAYS",str()),
        "pass_min_len": login_info.get("PASS_MIN_LEN",str()),
        "pass_warn_age": login_info.get(("PASS_WARN_AGE",str())),
        "dns": dns,
        "time_zone": time_zone,
        "NetworkManager": NetworkManager,
        "iptables": iptables,
        "kdump": kdump
    }
    print(data)

windows

import subprocess
import wmi
import re
import _winreg
from win32com.client import Dispatch
# gpedit.msc/computor/管理模板/网络/tcpip设置  WMI  "root\RSOP\Computer" 类RSOP_RegistryPolicySetting
cmd_6to4 = subprocess.check_output("netsh interface 6to4 show state")
service_6to4 = re.search("6to4 Service State[:\t\s]{0,}(?P<stat>\w+)", cmd_6to4).group('stat')
# cmd_firewall_service = subprocess.check_output("sc qc MpsSvc")
# win_firewall_service = re.search("START_TYPE[:\t\s\d]{0,}(?P<stat>\w+)",cmd_firewall_service).group("stat")
# time_zone = subprocess.check_output("tzutil /g").strip("\r\n").strip()
service = wmi.WMI()
objWMIService = Dispatch("WbemScripting.SWbemLocator")
conn_server = objWMIService.ConnectServer('localhost', "root\CIMV2")
# 时区  sql查询跟Win32_TimeZone()都行 select  StandardName from Win32_TimeZone
sql = 'SELECT StartMode FROM Win32_service where name = "MpsSvc" '
col_items = conn_server.ExecQuery(sql, "WQL")
ts = service.Win32_TimeZone()
# iphlpsvc
win_firewall_service = str()
time_zone = str()
for x in ts:
    time_zone = x.StandardName
    if time_zone == u"中国标准时间":
        time_zone = "China Standard Time"
for y in col_items:
    win_firewall_service = "{mode}_start".format(mode=y.StartMode).upper()
network_confs = service.Win32_NetworkAdapterConfiguration(IPEnabled=True)
dns = str()
if len(network_confs) < 1:
    print("没有找到可用的网络适配器")
    exit()
for network_conf in network_confs:
    if EASYOPS_LOCAL_IP in network_conf.IPAddress:
        dns = ",".join(network_conf.DNSServerSearchOrder)
i8042prt_path = r"SYSTEM\CurrentControlSet\Services\i8042prt\Parameters"
kbdhid_path = r"SYSTEM\CurrentControlSet\Services\kbdhid\Parameters"
crash_control_path = r"SYSTEM\CurrentControlSet\Control\CrashControl"
i8042prt_handle = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, i8042prt_path)
kbdhid_handle = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, kbdhid_path)
crash_control_handle = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, crash_control_path)
i8042prt = None
kbdhid = None
nmi_crash_dump = None
crash_dump_enabled =None
try:
    i8042prt, _type1 = _winreg.QueryValueEx(i8042prt_handle, "CrashOnCtrlScroll")
    kbdhid, _type2 = _winreg.QueryValueEx(kbdhid_handle, "CrashOnCtrlScroll")
    nmi_crash_dump,_type3 = _winreg.QueryValueEx(kbdhid_handle, "NMICrashDump")
    crash_dump_enabled,_type4 = _winreg.QueryValueEx(kbdhid_handle, "CrashDumpEnabled")
except Exception as e:
    pass
data={
    "service_6to4": service_6to4,
    "win_firewall_service": win_firewall_service,
    "time_zone": time_zone,
    "dns": dns,
    "i8042prt": i8042prt,
    "kbdhid": kbdhid,
    "nmi_crash_dump": nmi_crash_dump,
    "crash_dump_enabled": crash_dump_enabled,
    "win_firewall": "OFF",
    "location": "China",
    "remote_desktop": "Allow",
    "user_access_control": "Never Notify",
    "windows_update": "Disabled",
    "maximum_security_log_size": "131072 kilobytes",
    "retention_method_for_security_log": "As needed",
    "audit_logon_events": "Success,Failure",
    "interactive_logon:": "Enabled",
    "deny_log_on_through_terminal": "Administrator"

}
print(data)

 

posted @ 2019-07-25 13:31  林夕之风  阅读(247)  评论(0)    收藏  举报