基线检查工具Python代码

# coding=utf-8
'''
Created on 2017年11月3日

@author: Administrator
'''
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4 import QtWebKit

from PyQt4 import QtNetwork

# 处理中文问题
import sys, json

# 通过os模块调用系统命令.os模块可以跨平台使用
import os
# 通过wmi可以访问、配置、管理和监视几乎所有的Windows资源
import wmi
# 获取系统的信息
import platform
# 获取cpu 内存 硬盘信息
import psutil
# 用来访问注册表
import winreg
# 检查网卡冗余
import socket
# windows日志
import mmap
import contextlib
# from Evtx.Evtx import FileHeader
# from Evtx.Views import evtx_file_xml_view
from xml.dom import minidom
# sqllist3数据库
import sqlite3
# 获取时间
import datetime
# 导出excel
import xlwt
# 导入多线程
import qthread
import threading
# 时间延迟
import time
# 查看是否安装了raid
import megacli

# 多余的服务
dontService = ['Alerter', 'Clipbook', 'Computer Browser', 'DHCP Client', 'Messenger', 'Remote Registry Service',
               'Routing and Remote Access', 'Telnet', 'World Wide Web Publishing', 'Service', 'Print Spooler',
               'Terminal Service', 'Task Scheduler']
# 杀毒软件
killVirusSoftware = ['QQPCRTP.exe', '360tray.exe']
killVirusSoftwareName = {'QQPCRTP.exe': '腾讯安全管家', '360tray.exe': '360杀毒'}

hashMapResult = {}


# 生成windows安全策略文件在C盘
def buildWindowsSecurityPolicy():
    a = os.popen("secedit /export /cfg c:\gp.inf")
    a.close()


# 获取windos策略文件,生成策略文件字典
def windowsSecurityPolicyToDict():
    # 声明字典
    hashmap = {"a": 1}
    # 特殊情况
    hashmap['ResetLockoutCount'] = 0
    hashmap['LockoutDuration'] = 0
    file = r"c:\gp.inf"
    f = open(file, "r", encoding="UTF-16LE")
    equ = "="
    spl = " = "
    while True:
        data = f.readline()
        if equ in data:
            if spl in data:
                strs = data.split(spl)
                hashmap[strs[0]] = strs[1].strip().lstrip().rstrip(',')
            else:
                strs = data.split(equ)
                hashmap[strs[0]] = strs[1].strip().lstrip().rstrip(',')
        if not data:
            break
    f.close()
    return hashmap


# 生成windows服务字典
def windowsServiceToDict():
    # 默认的sqlserver
    hashmap = {'SQL SERVER': 0}
    noStatu = 0
    for i in dontService:
        hashmap[i] = noStatu
    wmiobj = wmi.WMI()
    services = wmiobj.Win32_Service()
    for i in services:
        hashmap[str(i.Caption)] = i.State
    return hashmap


# 生成windows进程的字典
def windowsProcessToDict():
    # 默认的sqlserver
    hashmap = {'sqlservr.exe': 0}
    result = os.popen('tasklist /fo csv')
    res = result.read()
    for line in res.splitlines():
        process = line.split(",")
        newProcess = process[0].replace(process[0][0], '')
        hashmap[newProcess] = process[0]
    return hashmap


# 生成端口的字典
def portToDict():
    hashmap = {"135": 0, "139": 0, "445": 0}
    result = os.popen('netstat -na')
    res = result.read()
    for line in res.splitlines():
        if ("0.0.0.0:" in line):
            lines = line.split("0.0.0.0:")
            line0 = lines[1][0:5].strip()
            hashmap[line0] = line0
    return hashmap


# 生成公用的字典
def buildCommonMap():
    # 系统类型,是windows还是linux
    hashmap = {"systemType": platform.system()}
    # 系统的默认ttl值
    hashmap["Windows"] = 64
    hashmap["Windows NT"] = 128
    hashmap["Windows 2000"] = 128
    hashmap["Windows XP"] = 128
    hashmap["Windows 7"] = 64
    hashmap["Windows 98"] = 32
    hashmap["Linux"] = 64
    return hashmap


# 判断ttl是否被修改过
def getIsDefaultTTL():
    # return "true"
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                         r"System\CurrentControlSet\Services\Tcpip\Parameters")
    # winreg.SetValueEx(key, 'defaultttl', None, winreg.REG_DWORD, 41)
    # print(winreg.QueryValueEx(key, 'defaultttl')[0])
    if (commonMap[commonMap["systemType"]] == winreg.QueryValueEx(key,'defaultttl')[0]):
        # 0允许远程桌面连接
        return "true"
    else:
        return "false"
    winreg.CloseKey(key)
# 判断是否有杀毒软件
def getIsKillSoftware():
    for software in killVirusSoftware:
        len0 = len(windowsProcess)
        windowsProcess[software] = software
        if (len(windowsProcess) == len0):
            return software
    return "false"


# 获取cpu信息
def getCpuInfo():
    cpu_count = psutil.cpu_count(logical=False)  # 1代表单核CPU,2代表双核CPU
    xc_count = psutil.cpu_count()  # 线程数,如双核四线程
    cpu_slv = round((psutil.cpu_percent(1)), 2)  # cpu使用率
    list = [cpu_count, xc_count, cpu_slv]
    return list


# 获取内存信息
def getMemoryInfo():
    memory = psutil.virtual_memory()
    total_nc = round((float(memory.total) / 1024 / 1024 / 1024), 2)  # 总内存
    used_nc = round((float(memory.used) / 1024 / 1024 / 1024), 2)  # 已用内存
    free_nc = round((float(memory.free) / 1024 / 1024 / 1024), 2)  # 空闲内存
    syl_nc = round((float(memory.used) / float(memory.total) * 100), 2)  # 内存使用率
    ret_list = [total_nc, used_nc, free_nc, syl_nc]
    return ret_list


# 获取硬盘信息
def getDiskInfo():
    list = psutil.disk_partitions()  # 磁盘列表
    ilen = len(list)  # 磁盘分区个数
    i = 0
    retlist2 = []
    while i < ilen:
        diskinfo = psutil.disk_usage(list[i].device)
        total_disk = round((float(diskinfo.total) / 1024 / 1024 / 1024), 2)  # 总大小
        used_disk = round((float(diskinfo.used) / 1024 / 1024 / 1024), 2)  # 已用大小
        free_disk = round((float(diskinfo.free) / 1024 / 1024 / 1024), 2)  # 剩余大小
        syl_disk = diskinfo.percent

        retlist1 = [i, list[i].device, total_disk, used_disk, free_disk, syl_disk]  # 序号,磁盘名称,
        retlist2.append(retlist1)
        i = i + 1
    return retlist2


# 判断网络是否连接
def getIsInternet():
    result = os.popen('ping www.baidu.com')
    res = result.read()
    for line in res.splitlines():
        if ("正在" in line):
            return "true"


# 判断是否开启了桌面远程连接
def getIsDesktopConnection():
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control\Terminal Server")
    if (0 == winreg.QueryValueEx(key,'fDenyTSConnections')[0]):
        # 0允许远程桌面连接
        return 0
    else:
        # 1不允许远程桌面连接
        return 1
    winreg.CloseKey(key)


# 判断禁止进入系统BOIS进行设置
def getIsBanBios():
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\services\USBSTOR")

    if (3 == winreg.QueryValueEx(key,'Start')[0]):
        # 允许
        return 3
    else:
        # 不允许
        return 4
    winreg.CloseKey(key)


# 判断是否开启默认分区共享
def getIsSharedPartitions():
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\services\LanmanServer\Parameters")
    if (0 == winreg.QueryValueEx(key,'AutoShareServer')[0]):
        # 已关闭分区默认共享
        return 0
    else:
        # 开启分区默认共享
        return 1
    winreg.CloseKey(key)


# 判断是否开启默认共享
def getIsShared():
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\services\LanmanServer\Parameters")
    if (0 == winreg.QueryValueEx(key,'AutoShareWks')[0]):
        # 已关闭默认共享
        return 0
    else:
        # 开启默认共享
        return 1
    winreg.CloseKey(key)


# 判断是否是默认日志大小
def getIsDefalutLogSize():
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\services\eventlog\Security")
    if (20971520 == winreg.QueryValueEx(key, 'MaxSize')[0]):
        # 默认日志大小
        return 0
    else:
        return 1
    winreg.CloseKey(key)


# 获取日志的地址
def getLogPaths():
    list = []
    # Security日志文件地址
    key0 = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\services\eventlog\Security")
    try:
        i = 0
        while True:
            k0 = winreg.EnumValue(key0, i)
            i += 1
            # print(k)
            if ('File' in k0 and 'DisplayNameFile' not in k0):
                paths = k0[1]
                list.append(paths)
    except Exception:
        pass
        # print()
    winreg.CloseKey(key0)
    # Application日志文件地址
    key1 = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\services\eventlog\Application")
    try:
        i = 0
        while True:
            k1 = winreg.EnumValue(key1, i)
            i += 1
            # print(k)
            if ('File' in k1 and 'DisplayNameFile' not in k1):
                paths = k1[1]
                list.append(paths)
    except Exception:
        pass
        # print()
    winreg.CloseKey(key1)

    # System日志文件地址
    key2 = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\services\eventlog\System")
    try:
        i = 0
        while True:
            k2 = winreg.EnumValue(key2, i)
            i += 1
            # print(k)
            if ('File' in k2 and 'DisplayNameFile' not in k2):
                paths = k2[1]
                list.append(paths)
    except Exception:
        pass
        # print()
    winreg.CloseKey(key2)
    # 系统盘
    systemDisk = os.getenv("SystemDrive")
    listNew = []
    for path in list:
        path1 = path.replace('%SystemRoot%', systemDisk + "//Windows")
        listNew.append(path1)
        # print(path1)
    return listNew


# \system32\winevt\Logs\Application.evtx

# 过滤掉不需要的事件,输出感兴趣的事件
def InterestEvent(xml, EventID):
    xmldoc = minidom.parseString(xml)
    root = xmldoc.documentElement
    # print(root.childNodes)
    # 获取EventID节点的事件ID
    # booknode=root.getElementsByTagName('event')
    # for booklist in booknode:


#     bookdict={}
#     bookdict['id']=booklist.getAttribute('id')
#     bookdict['head']=booklist.getElementsByTagName('head')[0].childNodes[0].nodeValue.strip()
#     bookdict['name']=booklist.getElementsByTagName('name')[0].childNodes[0].nodeValue.strip()
#     bookdict['number']=booklist.getElementsByTagName('number')[0].childNodes[0].nodeValue.strip()
#     bookdict['page']=booklist.getElementsByTagName('page')[0].childNodes[0].nodeValue.strip()
# if EventID == eventId:
#     print xml


# 判断是否是打开防火墙
def getIsFirewall():
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                         r"SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\StandardProfile")
    if (0 == winreg.QueryValueEx(key, 'EnableFirewall')[0]):
        # 关闭防火墙
        return 0
    else:
        # 打开防火墙
        return 1
    winreg.CloseKey(key)


# 判断网卡冗余
def getIsNicRedundancy():
    i = 0
    for ip in socket.gethostbyname_ex(socket.gethostname())[2]:
        localIP = ip
        i = i + 1
        if (i >= 2):
            return 1
    return 0


# 判断是否安装了raid
def getIsRaid():
    try:
        cli = megacli.MegaCLI()
        cli.bbu()
        # 安装了
        return 1
    except:
        # 没有安装
        return 0


# 判断用户是否需要密码
def getIsRequiredPassword():
    result = os.popen('wmic useraccount list full')
    res = result.read()
    i = 0
    count = 0
    name0 = str(securityPolicy['NewAdministratorName'])
    name = name0.replace(name0[0], '')
    for line in res.splitlines():
        if (name in line):
            i = 1
        if (i == 1):
            count = count + 1
        if (i == 1 and 'PasswordRequired=TRUE' in line and count <= 11):
            return 1
        if (count > 12):
            return 0


# 获取管理员下面所有的用户
def buildUserList():
    result = os.popen('Net Localgroup administrators')
    res = result.read()
    list = []
    count = 0
    for line in res.splitlines():
        if ('成功完成' in line):
            return list
        if (count == 1):
            list.append(line)
        if ('---' in line):
            count = 1


# 创建数据库和用户表
def buildDatabase():
    conn = sqlite3.connect('baseline.db')
    # print("Opened database successfully")
    c = conn.cursor()
    c.execute('''CREATE TABLE USER
           (ID INT PRIMARY KEY     NOT NULL,
           NAME           TEXT    NOT NULL,
           AGE            INT     NOT NULL,
           LOGIN_TIME     timestamp NOT NULL,
           ADDRESS        CHAR(50),
           SALARY         REAL);''')
    c.execute("INSERT INTO USER (ID,NAME,AGE,LOGIN_TIME,ADDRESS,SALARY) \
          VALUES (1, 'duke', 32,'2016-01-22 08:45:50', 'California', 20000.00 )");
    # print("Table created successfully")
    conn.commit()
    conn.close()


# 显示结果1身份鉴别
def printResult1_2():
    hashMap = {}
    # print("任务2-->用户名称:" + securityPolicy['NewAdministratorName'])
    task_2_0 = "不需要口令"
    requiredPassword = getIsRequiredPassword()

    if (requiredPassword == 1):
        task_2_0 = "需要口令"
    # print("任务2-->是否需要用户口令:" + task_2_0)
    hashMap["NewAdministratorName"] = securityPolicy['NewAdministratorName'][1:][:-1]
    hashMap["requiredPassword_dict"] = task_2_0
    hashMap["requiredPassword"] = requiredPassword
    return hashMap

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值