# coding=utf-8
'''
Created on 2017年11月3日@author: Administrator
'''
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4 import QtWebKitfrom 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'] = 0hashmap['LockoutDuration'] = 0file = 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:breakf.close()return hashmap# 生成windows服务字典
def windowsServiceToDict():# 默认的sqlserverhashmap = {'SQL SERVER': 0}noStatu = 0for i in dontService:hashmap[i] = noStatuwmiobj = wmi.WMI()services = wmiobj.Win32_Service()for i in services:hashmap[str(i.Caption)] = i.Statereturn hashmap# 生成windows进程的字典
def windowsProcessToDict():# 默认的sqlserverhashmap = {'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] = line0return hashmap# 生成公用的字典
def buildCommonMap():# 系统类型,是windows还是linuxhashmap = {"systemType": platform.system()}# 系统的默认ttl值hashmap["Windows"] = 64hashmap["Windows NT"] = 128hashmap["Windows 2000"] = 128hashmap["Windows XP"] = 128hashmap["Windows 7"] = 64hashmap["Windows 98"] = 32hashmap["Linux"] = 64return 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] = softwareif (len(windowsProcess) == len0):return softwarereturn "false"# 获取cpu信息
def getCpuInfo():cpu_count = psutil.cpu_count(logical=False)  # 1代表单核CPU,2代表双核CPUxc_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 = 0retlist2 = []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.percentretlist1 = [i, list[i].device, total_disk, used_disk, free_disk, syl_disk]  # 序号,磁盘名称,retlist2.append(retlist1)i = i + 1return 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 0else:# 1不允许远程桌面连接return 1winreg.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 3else:# 不允许return 4winreg.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 0else:# 开启分区默认共享return 1winreg.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 0else:# 开启默认共享return 1winreg.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 0else:return 1winreg.CloseKey(key)# 获取日志的地址
def getLogPaths():list = []# Security日志文件地址key0 = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\services\eventlog\Security")try:i = 0while 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 = 0while 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 = 0while 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 0else:# 打开防火墙return 1winreg.CloseKey(key)# 判断网卡冗余
def getIsNicRedundancy():i = 0for ip in socket.gethostbyname_ex(socket.gethostname())[2]:localIP = ipi = i + 1if (i >= 2):return 1return 0# 判断是否安装了raid
def getIsRaid():try:cli = megacli.MegaCLI()cli.bbu()# 安装了return 1except:# 没有安装return 0# 判断用户是否需要密码
def getIsRequiredPassword():result = os.popen('wmic useraccount list full')res = result.read()i = 0count = 0name0 = str(securityPolicy['NewAdministratorName'])name = name0.replace(name0[0], '')for line in res.splitlines():if (name in line):i = 1if (i == 1):count = count + 1if (i == 1 and 'PasswordRequired=TRUE' in line and count <= 11):return 1if (count > 12):return 0# 获取管理员下面所有的用户
def buildUserList():result = os.popen('Net Localgroup administrators')res = result.read()list = []count = 0for line in res.splitlines():if ('成功完成' in line):return listif (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_0hashMap["requiredPassword"] = requiredPasswordreturn hashMap

基线检查工具Python代码相关推荐

  1. 服务器安全基线检查(Python)代码执行

    # coding=utf-8 ''' Created on 2017年11月3日@author: Administrator ''' from PyQt4 import QtCore from PyQ ...

  2. 从静态检查工具谈代码编程规范

    提升自身编程能力是每一个码农的追求,也许我们每日都可以写上几百几千行代码,抑或每日只能修修补补添加几行代码,可是编写代码的行数的增加确实是提升编程能力的体现吗?从我个人的理解来看并不是这样. 从学校到 ...

  3. python--如何使用 Pylint 来检查分析Python 代码

    Pylint 是什么 Pylint 是一个 Python 代码分析工具,它分析 Python 代码中的错误,查找不符合代码风格标准(Pylint 默认使用的代码风格是 PEP 8,具体信息,请参阅参考 ...

  4. java代码检查工具pmd_Java 代码检查工具 PMD

    PMD是一款采用BSD协议发布的Java程序代码检查工具.该工具可以做到检查Java代码中是否含有未使用的变量.是否含有空的抓取块.是否含有不必要的对象等.该软件功能强大,扫描效率高,是Java程序员 ...

  5. 基线检查工具_最新版CAD燕秀工具箱2.87(支持20042021)

    好课推荐: 零基础CAD:点我CAD家装:点我 周站长CAD:点我CAD机械:点我revit教程:点我CAD建筑:点我CAD三维:点我全屋定制:点我 ps教程:点我苹果版CAD:点我 3dmax教程: ...

  6. python代码风格

    pep8:Python代码风格检查工具 Python官网定义的代码风格 PEP 0008 – Style Guide for Python Code. pep8是检测编码风格是否符合 PEP 0008 ...

  7. Google出品的Python代码静态类型分析器:Pytype

    Pytype检查并推断Python代码的类型--不需要类型注解.Pytype可以: 使用lint检查纯Python代码,标记常见错误,如属性名拼写错误.不正确的函数调用,等等更多,它甚至可以跨文件. ...

  8. python代码质量检查工具_python代码检查工具pylint 让你的python更规范

    复制代码 代码如下: #coding:utf-8 ''' a test function module ''' import urllib import time def fetch(url): '' ...

  9. python代码规范工具_如何检查python3中的代码规范

    如何检查python3中的代码规范 发布时间:2020-11-16 09:40:48 来源:亿速云 阅读:77 作者:小新 这篇文章给大家分享的是有关如何检查python3中的代码规范的内容.小编觉得 ...

  10. python代码风格检查工具──pylint

    pylint是一个python代码检查工具,可以帮助python程序员方便地检查程序代码的语法和风格,通过这个工具,可以使你的python代码尽量保持完美,哈哈. 具体可以检查什么东西呢? 比如你写了 ...

最新文章

  1. KR C 传统C语言的函数定义
  2. Linux 解决ssh连接慢的问题
  3. android studio资源二进制,无法自动检测ADB二进制文件 – Android Studio
  4. 商业方向的大数据专业_结合当前的人才需求趋势,大数据专业考研时可以选择哪些主攻方向...
  5. 路由器太远手机接收不到信号怎么办
  6. Redis知识点笔记总结
  7. python贴吧数据可视化_Python数据可视化
  8. 互联网广告与计算广告学
  9. HTML-淘宝导航条
  10. 【数据分析】京东2019校招数据分析工程师笔试题
  11. 世界读书日送你畅销好书!前所未有4折购书福利
  12. win10硬盘锁怎么解除_win10系统如何解锁bitlocker的硬盘加密
  13. 拼多多面试官没想到ThreadLocal我用得这么溜,人直接傻掉
  14. 谷歌浏览器将ssd盘上的缓存目录迁移至机械硬盘
  15. html时间日期 年月日时分秒,年月日时分秒的即时显示
  16. 口令不符合oracle建议标准,INS-30011 输入的ADMIN口令不符合Oracle建议的标准
  17. 中标linux+银河麒麟=中标麒麟
  18. Mars的自语重出江湖,祝大家端午节安康
  19. Struts + hibernate +spring课堂笔记
  20. 优质的MES管理系统,需具备这四个特性

热门文章

  1. Windows Server - NIC Teaming
  2. 李智慧-我的全栈之路导师之一
  3. unity运行时修改光源的颜色,变成白色
  4. react-app-rewired 修改 react 项目默认端口号
  5. 用计算机发送电子邮件,用英语解释一下发送电子邮件的过程 用计算机语言来说一下,大概400到500个英文单词...
  6. 【MySQL】014-join连接语句用法详解
  7. hutool的BeanUtil
  8. ALPS 2.3.0 安装教程
  9. 模拟退火算法求解--顺序约束的路由部署问题
  10. 【那些年我们一起看过的论文】之《Handwritten Digit Recognition with a Back-Propagation Network》