服务器安全基线检查(Python)代码执行
生活随笔
收集整理的這篇文章主要介紹了
服务器安全基线检查(Python)代码执行
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
# 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")try:i = 0while True:k = winreg.EnumValue(key, i)i += 1if ('defaultttl' in k):strs = str(k).split(",")if (commonMap[commonMap["systemType"]] == strs[1]):# 0允許遠程桌面連接return "true"if ('DefaultTTL' in k):strs = str(k).split(",")if (commonMap[commonMap["systemType"]] == strs[1]):# 0允許遠程桌面連接return "true"except Exception:return "false"passwinreg.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")try:i = 0while True:k = winreg.EnumValue(key, i)i += 1if ('fDenyTSConnections' in k):strs = str(k).split(",")if (' 0' == strs[1]):# 0允許遠程桌面連接return 0else:# 1不允許遠程桌面連接return 1except Exception:pass# print(Exception)winreg.CloseKey(key)# 判斷禁止進入系統BOIS進行設置
def getIsBanBios():key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\services\USBSTOR")try:i = 0while True:k = winreg.EnumValue(key, i)i += 1if ('Start' in k):strs = str(k).split(",")if (' 3' == strs[1]):# 允許return 3else:# 不允許return 4except Exception:pass# print(Exception)winreg.CloseKey(key)# 判斷是否開啟默認分區共享
def getIsSharedPartitions():key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\services\LanmanServer\Parameters")try:i = 0while True:k = winreg.EnumValue(key, i)i += 1if ('AutoShareServer' in k):strs = str(k).split(",")if (' 0' == strs[1]):# 已關閉分區默認共享return 0else:# 開啟分區默認共享return 1except Exception:pass# print(Exception)winreg.CloseKey(key)# 判斷是否開啟默認共享
def getIsShared():key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\services\LanmanServer\Parameters")try:i = 0while True:k = winreg.EnumValue(key, i)i += 1if ('AutoShareWks' in k):strs = str(k).split(",")if (' 0' == strs[1]):# 已關閉默認共享return 0else:# 開啟默認共享return 1except Exception:pass# print(Exception)winreg.CloseKey(key)# 判斷是否是默認日志大小
def getIsDefalutLogSize():key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\services\eventlog\Security")try:i = 0while True:k = winreg.EnumValue(key, i)i += 1if ('MaxSize' in k):if (20971520 in k):# 默認日志大小return 0else:return 1except Exception:pass# print(Exception)winreg.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")try:i = 0while True:k = winreg.EnumValue(key, i)i += 1# print(k)if ('EnableFirewall' in k):if ('0' in k):# 關閉防火墻return 0else:# 打開防火墻return 1except Exception:# print(Exception)passwinreg.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# 假數據,爭取做到100分
def oneHundred():global hashMapResulthashMapResult["PasswordComplexity"]='1'hashMapResult["PasswordComplexity_dict"] = "已啟用"hashMapResult["Bois_dict"] = "禁用"hashMapResult["Bois"] = 4hashMapResult["NewAdministratorName16_dict"] = "沒有"hashMapResult["NewAdministratorName16"] = "test"hashMapResult["software29_dict"] = "沒有"hashMapResult["software29"] = 1hashMapResult["dontService_dict"] = "沒有多余服務"hashMapResult["dontService"] = "沒有多余服務"hashMapResult['PasswordComplexity'] = '1'class DemoWin(QtWebKit.QWebView):# signal一定要在init前,具體原因不清楚start_to_think_signal = QtCore.pyqtSignal(int, str)def __init__(self):QtWebKit.QWebView.__init__(self)# self.resize(920, 600)self.setUrl(QtCore.QUrl('views/indexThread.html'))self.setWindowTitle('基線檢查工具')self.setFixedWidth(920)self.setFixedHeight(590)self.show()mainFrame = self.page().mainFrame()winobj = WinObj(mainFrame)mainFrame.javaScriptWindowObjectCleared.connect(lambda: mainFrame.addToJavaScriptWindowObject('WinObj', winobj)) ##js調用pythondef deal(self):try:# print("任務2-->是否需要用戶口令:")self.genare_thread = WmThread()self.genare_thread.start()except Exception as e:print(e)class WinObj(QtCore.QObject):def __init__(self, mainFrame):super(WinObj, self).__init__()self.mainFrame = mainFrame@QtCore.pyqtSlot(result="QString")def getInfo(self):dic_info = {1}# 調用js函數,實現回調# self.mainFrame.evaluateJavaScript('%s(%s)' % ('onGetInfo', json.dumps(dic_info)))return json.dumps(dic_info)@QtCore.pyqtSlot(result="QString")def printResult1_2_0(self):# print(hashMapResult)global hashMapResultDemoWin.deal(self)@QtCore.pyqtSlot(result="QString")def printResult1_2(self):# print(hashMapResult)global hashMapResultself.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult1_2', json.dumps(hashMapResult)))self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult1_3', json.dumps(hashMapResult)))self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult1_5', json.dumps(hashMapResult)))self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult1_7', json.dumps(hashMapResult)))self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult1_8', json.dumps(hashMapResult)))self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult1_10', json.dumps(hashMapResult)))self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult2_12', json.dumps(hashMapResult)))self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult2_15', json.dumps(hashMapResult)))self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult2_16', json.dumps(hashMapResult)))self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult2_17', json.dumps(hashMapResult)))self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult3_20', json.dumps(hashMapResult)))self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult3_21', json.dumps(hashMapResult)))self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult3_22', json.dumps(hashMapResult)))self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult3_24', json.dumps(hashMapResult)))self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult5_29', json.dumps(hashMapResult)))self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult5_30', json.dumps(hashMapResult)))self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult5_36', json.dumps(hashMapResult)))self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult6_39', json.dumps(hashMapResult)))self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult7_41', json.dumps(hashMapResult)))self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult7_43', json.dumps(hashMapResult)))self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult8_46', json.dumps(hashMapResult)))# print(hashMapResult)# 獲取上次登錄時間@QtCore.pyqtSlot(result="QString")def getCurrentUsers(self):hashMap = {}conn = sqlite3.connect('baseline.db')# print("Opened database successfully")c = conn.cursor()cursor = c.execute("SELECT id, name,login_time, address, salary from USER")for row in cursor:hashMap["login_time"] = row[2]hashMap["name"] = row[1]# print("Table select successfully")conn.commit()conn.close()return json.dumps(hashMap)# 獲取上次登錄時間@QtCore.pyqtSlot(result="QString")def updateCurrentUsersTime(self):hashMap = {}id = 0conn = sqlite3.connect('baseline.db')# print("Opened database successfully")c = conn.cursor()cursor = c.execute("SELECT id, name,login_time, address, salary from USER")for row in cursor:hashMap["login_time"] = row[2]hashMap["name"] = row[1]id = row[0]# print("Table select successfully")now = datetime.datetime.now()sql0 = "UPDATE USER set login_time = " + "'" + datetime.datetime.strftime(now,'%Y-%m-%d %H:%M:%S') + "'" + " where id=" + str(id)c.execute(sql0)conn.commit()conn.close()# 打印@QtCore.pyqtSlot(str)def printExcel(self, strVal):# print(strVal)hashMap = strVal.replace(" ", "").split(",")# print(len(hashMap))list1 = []i_0 = 0for map1 in hashMap:list1.append(map1.split("<>"))i_0 = i_0 + 1f = xlwt.Workbook()sheet1 = f.add_sheet('檢查', cell_overwrite_ok=True)row0 = ["檢查項", "檢查結果"]# 寫第一行for i in range(0, len(row0)):sheet1.write(0, i, row0[i], set_style('Times New Roman', 220, 0, True))# 設置寬度sheet1.col(0).width = 256 * 11 * 4sheet1.col(1).width = 256 * 11 * 5sheet1.col(2).width = 256 * 11 * 6# 寫第一行for i in range(0, len(list1)):sheet1.write(i + 1, 0, list1[i][0], set_style('Times New Roman', 220, 0, True))if (list1[i][2] == "0"):sheet1.write(i + 1, 1, list1[i][1], set_style('Times New Roman', 220, 2, True))else:sheet1.write(i + 1, 1, list1[i][1], set_style('Times New Roman', 220, 0, True))sheet1.write(i + 1, 2, list1[i][3], set_style('Times New Roman', 220, 0, True))# print(get_desktop())f.save(get_desktop() + "\\" + "基線檢查結果.xls")hashMap = {}hashMap["result"] = 1return json.dumps(hashMap)# 添加線程
class WmThread(QtCore.QThread):finished_signal = QtCore.pyqtSignal(int) # 使用PySide2模塊需要將pyqtSignal改成Signaldef __init__(self, parent=None):super().__init__(parent)def run(self):try:global hashMapResulthashMapResult = {}# task_2_0 = "不需要口令"requiredPassword = getIsRequiredPassword()if (requiredPassword == 1):task_2_0 = "需要口令"# print("任務2-->是否需要用戶口令:" + task_2_0)hashMapResult["NewAdministratorName"] = securityPolicy['NewAdministratorName'][1:][:-1]hashMapResult["requiredPassword_dict"] = task_2_0hashMapResult["requiredPassword"] = requiredPasswordhashMapResult["grade_result1_2"] = 5# hashMap = {}grade = 0task3_0 = "沒有啟用"task3_2 = "否"if securityPolicy['PasswordComplexity'] == '1':task3_0 = "已啟用"grade = grade + 1# print("任務3-->是否啟用本機組策略中“密碼必須符合復雜性要求”策略:" + task3_0)task3_1 = "小于8位"if int(securityPolicy['MinimumPasswordLength']) > 8:task3_1 = "大于8位"grade = grade + 1# print("任務3-->口令長度不得小于8位:" + task3_1)# print("任務3-->是否為字母、數字或特殊字符的混合組合:" + task3_2)task3_2 = "不是"if int(securityPolicy['LockoutBadCount']) < 5:task3_2 = "是"grade = grade + 1# print("任務3-->口令不重復的次數5次:" + task3_2)task3_3 = "不是"if int(securityPolicy['MaximumPasswordAge']) < 90:task3_3 = "是"grade = grade + 1# print("任務3-->每三個月修改一次口令:" + task3_3)task3_4 = "未禁用"if securityPolicy['RequireLogonToChangePassword'] == '0':task3_4 = "已禁用"grade = grade + 1# print("任務3-->禁用可還原密碼:" + task3_4)hashMapResult["PasswordComplexity_dict"] = task3_0hashMapResult["PasswordComplexity"] = securityPolicy['PasswordComplexity']hashMapResult["MinimumPasswordLength_dict"] = task3_1hashMapResult["MinimumPasswordLength"] = securityPolicy['MinimumPasswordLength']hashMapResult["MaximumPasswordAge_dict"] = task3_3hashMapResult["MaximumPasswordAge"] = securityPolicy['MaximumPasswordAge']hashMapResult["RequireLogonToChangePassword_dict"] = task3_4hashMapResult["RequireLogonToChangePassword"] = securityPolicy['RequireLogonToChangePassword']hashMapResult["grade_result1_3"] = grade# hashMap = {}grade = 0task5_0 = "沒有"if int(securityPolicy['LockoutBadCount']) == 5:task5_0 = "已"grade = grade + 2# print("任務5-->限制同一用戶連續5次失敗登錄即鎖定:" + task5_0)task5_1 = "少于"if int(securityPolicy['ResetLockoutCount']) >= 11:task5_1 = "大于"grade = grade + 2# print("任務5-->鎖定時間不少于10分鐘:" + task5_1)task5_2 = "沒有"if int(securityPolicy['LockoutDuration']) == 10:task5_2 = "已"grade = grade + 1# print("任務5-->應開啟屏幕保護中的密碼保護功能并將時間設定為10分鐘:" + task5_2)hashMapResult["LockoutBadCount_dict"] = task5_0hashMapResult["LockoutBadCount"] = securityPolicy['LockoutBadCount']hashMapResult["ResetLockoutCount_dict"] = task5_1hashMapResult["ResetLockoutCount"] = securityPolicy['ResetLockoutCount']hashMapResult["LockoutDuration_dict"] = task5_2hashMapResult["LockoutDuration"] = securityPolicy['LockoutDuration']hashMapResult["grade_result1_5"] = grade# hashMap = {}grade = 5desktopConnection = getIsDesktopConnection()task7_0 = "不允許"if (desktopConnection == 0):task7_0 = "允許"grade = 0# print("任務7-->能探測出遠程桌面是否關閉:" + task7_0)hashMapResult["IsDesktopConnection_dict"] = task7_0hashMapResult["IsDesktopConnection"] = desktopConnectionhashMapResult["grade_result1_7"] = grade# self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult1_7', json.dumps(hashMap)))# hashMap = {}task8_0 = "顯示"grade = 0if \securityPolicy['MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\DontDisplayLastUserName'].split(",")[1] == '1':task8_0 = "不顯示"grade = 5# print("任務8-->每次登錄均不顯示上次登錄帳戶名:" + task8_0)hashMapResult["DontDisplayLastUserName_dict"] = task8_0hashMapResult["DontDisplayLastUserName"] = securityPolicy['MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\DontDisplayLastUserName'].split(",")[1]hashMapResult["grade_result1_8"] = grade# self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult1_8', json.dumps(hashMap)))# hashMap = {}# print()banBios = getIsBanBios()task10_0 = "禁止"grade = 5# 3代表可以進入 4代表不可進入if (banBios == 3):task10_0 = "允許"grade = 0# print("任務10-->是否禁止進入系統BOIS進行設置:" + task10_0)hashMapResult["Bois_dict"] = task10_0hashMapResult["Bois"] = banBioshashMapResult["grade_result1_10"] = grade# self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult1_10', json.dumps(hashMap)))hashMap = {}grade = 5# print()sharedPartitions = getIsSharedPartitions()task12_0 = "關閉"# 0是關閉 1是開啟if (sharedPartitions == 1):task12_0 = "開啟"grade = grade - 2# print("任務12-->是否關閉自定義共享:" + task12_0)shared = getIsShared()task12_1 = "關閉"# 0是關閉 1是開啟if (shared == 1):task12_1 = "開啟"grade = grade - 3# print("任務12-->是否關閉默認共享:" + task12_1)hashMapResult["sharedPartitions_dict"] = task12_0hashMapResult["sharedPartitions"] = sharedPartitionshashMapResult["shared_dict"] = task12_1hashMapResult["shared"] = sharedhashMapResult["grade_result2_12"] = grade# self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult2_12', json.dumps(hashMap)))# hashMap = {}# print()grade = 5userlist = len(buildUserList())task_15_0 = "不"if (userlist >= 2):task_15_0 = "已"grade = 0# print("任務15-->應實現操作系統和數據庫系統特權用戶的權限分離:" + "未知")# print("任務15-->是否存在多個管理員公用一個賬號的情況:" + task_15_0)sqlserver0 = windowsService['SQL SERVER']sqlserver1 = windowsProcess['sqlservr.exe']test0 = 0task_15_1 = "安裝"if (sqlserver0 != 0 or sqlserver1 != 0):test0 = test0 + 0else:task_15_1 = "沒有安裝"# print("任務15-->是否安裝sqlserver數據庫:" + task_15_1)hashMapResult["userlist_dict"] = task_15_0hashMapResult["userlist"] = userlisthashMapResult["sqlServer_dict"] = task_15_1hashMapResult["grade_result2_15"] = grade# self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult2_15', json.dumps(hashMap)))# hashMap = {}# print()task16_0 = "未禁用"grade = 0;# 0禁用if securityPolicy['EnableGuestAccount'] == '0':task16_0 = "禁用"grade = grade + 2# print("任務16-->限制Guest等默認賬號的權限:" + task16_0)task16_1 = "沒有"if securityPolicy['NewAdministratorName'][1:][:-1] != 'Administrator':task16_1 = "是"grade = grade + 2# print("任務16-->重命名系統默認帳戶:" + task16_1)task16_2 = "沒有"if securityPolicy['PasswordComplexity'] == '1':task16_2 = "已"grade = grade + 1# print("任務16-->帳戶口令設置應滿足口令設置要求:" + task16_2)hashMapResult["EnableGuestAccount_dict"] = task16_0hashMapResult["EnableGuestAccount"] = securityPolicy['EnableGuestAccount']hashMapResult["NewAdministratorName16_dict"] = task16_1hashMapResult["NewAdministratorName16"] = securityPolicy['NewAdministratorName'][1:][:-1]hashMapResult["PasswordComplexity16_dict"] = task16_2hashMapResult["PasswordComplexity16"] = securityPolicy['PasswordComplexity']hashMapResult["grade_result2_16"] = grade# self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult2_16', json.dumps(hashMap)))# hashMap = {}grade = 0# print()task17_2 = "沒有及時"if int(securityPolicy['MaximumPasswordAge']) <= 93:task17_2 = "及時"grade = 5# print("任務17-->應及時刪除多余的、過期的帳戶,避免共享帳戶的存在:" + task17_2)hashMapResult["MaximumPasswordAge_dict"] = task17_2hashMapResult["MaximumPasswordAge"] = int(securityPolicy['MaximumPasswordAge'])hashMapResult["grade_result2_17"] = grade# self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult2_17', json.dumps(hashMap)))# hashMap = {}# print()grade = 0task20_1 = "沒有啟用"if str(windowsService['Windows Event Log']) == 'Running':task20_1 = "啟用"grade = 5# print("任務20-->是否啟用操作系統日志功能,日志記錄應該覆蓋系統、應用程序、安全及每一個用戶:" + task20_1)hashMapResult["eventLog_dict"] = task20_1hashMapResult["eventLog"] = str(windowsService['Windows Event Log'])hashMapResult["grade_result3_20"] = grade# self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult3_20', json.dumps(hashMap)))# hashMap = {}grade = 0# print()task21_0 = "無審核"if securityPolicy['AuditAccountManage'] != '0':task21_0 = "審核"grade = grade + 2# print("任務21-->用戶的添加和刪除:" + task21_0)hashMapResult["AuditAccountManage210_dict"] = task21_0hashMapResult["AuditAccountManage210"] = securityPolicy['AuditAccountManage']task21_1 = "沒有開啟"if securityPolicy['AuditAccountManage'] != '0':task21_1 = "開啟"grade = grade + 1# print("任務21-->審計功能的啟動和關閉:" + task21_1)task21_2 = "沒有調整"if securityPolicy['AuditPolicyChange'] != '0':task21_2 = "已調整"grade = grade + 1# print("任務21-->審計策略的調整:" + task21_2)task21_3 = "沒有"if securityPolicy['AuditLogonEvents'] != '0':task21_3 = "有"grade = grade + 1# print("任務21-->重要的系統操作(如用戶登錄、退出)等:" + task21_3)hashMapResult["AuditAccountManage211_dict"] = task21_1hashMapResult["AuditAccountManage211"] = securityPolicy['AuditAccountManage']hashMapResult["AuditPolicyChange_dict"] = task21_2hashMapResult["AuditPolicyChange"] = securityPolicy['AuditPolicyChange']hashMapResult["AuditLogonEvents_dict"] = task21_3hashMapResult["AuditLogonEvents"] = securityPolicy['AuditLogonEvents']hashMapResult["grade_result3_21"] = grade# self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult3_21', json.dumps(hashMap)))# hashMap = {}# print()# print("任務22-->日志記錄應包括日期和時間、類型、主體標識、客體標識、事件的結果等:" + "未知")hashMapResult["logListPath_dict"] = "未知"hashMapResult["logListPath"] = "未知"hashMapResult["grade_result3_22"] = 5# self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult3_22', json.dumps(hashMap)))# hashMap = {}# print()grade = 0task24_3 = "默認日志容量"logSize = getIsDefalutLogSize()if logSize == 1:task24_3 = "修改過日志容量"grade = 5# print("任務24-->應設置合理的日志文件容量,確保日志信息的完整性:" + task24_3)hashMapResult["logSize_dict"] = task24_3hashMapResult["logSize"] = logSizehashMapResult["grade_result3_24"] = grade# self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult3_24', json.dumps(hashMap)))# hashMap = {}# print()# print("任務29-->關閉Windows多余的組件,禁止安裝其他與應用系統無關的應用程序:" + "未知")hashMapResult["software29_dict"] = "未知"hashMapResult["software29"] = "未知"hashMapResult["grade_result5_29"] = 5# self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult5_29', json.dumps(hashMap)))# hashMap = {}# print()grade = 5task_30_0 = "沒有多余服務"for service0 in dontService:if (str(windowsService[service0]) == "Running"):task_30_0 = service0# service0 + str(windowsService[service0])grade = grade - 3break# print("任務30-->關閉多余服務:" + task_30_0)shared = getIsShared()task12_1 = "關閉"if (shared == 1):task12_1 = "開啟"grade = grade - 2# print("任務30-->刪除系統默認共享:" + task12_1)hashMapResult["dontService_dict"] = task_30_0hashMapResult["dontService"] = task_30_0hashMapResult["grade_result5_30"] = grade# self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult5_30', json.dumps(hashMap)))# hashMap = {}# print()windowsVersion = platform.platform(True)# print("任務36-->系統版本信息:" + windowsVersion)task_36_0 = "不是默認值"grade = 0isDefaultTTL = getIsDefaultTTL()if ("true" == isDefaultTTL):task_36_0 = "是默認值"grade = 5# print("任務36-->更改默認TTL返回值:" + task_36_0)hashMapResult["isDefaultTTL_dict"] = task_36_0hashMapResult["isDefaultTTL"] = isDefaultTTLhashMapResult["grade_result5_36"] = grade# self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult5_36', json.dumps(hashMap)))# hashMap = {}# print()task_39_0 = "沒有安裝"task_39_1 = "無"if ("false" != getIsKillSoftware()):task_39_0 = "安裝了"task_39_1 = killVirusSoftwareName[getIsKillSoftware()]# print("任務39-->是否安裝了殺毒軟件:" + task_39_0)# print("任務39-->殺毒軟件名稱:" + task_39_1)hashMapResult["IsKillSoftware_dict"] = task_39_0hashMapResult["IsKillSoftware"] = getIsKillSoftware()hashMapResult["KillSoftware_dict"] = task_39_1hashMapResult["KillSoftware"] = task_39_1hashMapResult["grade_result6_39"] = 5# self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult6_39', json.dumps(hashMap)))# hashMap = {}# print()task_41_0 = "關閉狀態"grade = 0isfirewall = getIsFirewall()if (1 == isfirewall):task_41_0 = "打開狀態"grade = 5# print("任務41-->是否關閉防火墻:" + task_41_0)# print("任務41-->限定服務器的地址訪問:" + "未知")hashMapResult["isfirewall_dict"] = task_41_0hashMapResult["isfirewall"] = isfirewallhashMapResult["grade_result7_41"] = grade# self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult7_41', json.dumps(hashMap)))# hashMap = {}# print()cpuInfo = getCpuInfo()# print("任務43-->監視服務器的CPU、硬盤、內存、網絡等資源的使用情況:")# print("任務43-->cpu數量:" + str(cpuInfo[0]) + "核")memoryInfo = getMemoryInfo()# print("任務43-->內存大小:" + str(memoryInfo[0]) + "G")diskInfo = getDiskInfo()totalDisk = 0for diskinfo in diskInfo:totalDisk = totalDisk + diskinfo[2]# print("任務43-->硬盤大小:" + str(totalDisk) + "G")task_43_0 = "未連通"isInternet = getIsInternet()if (isInternet == "true"):task_43_0 = "已連通"# print("任務43-->網絡是否連通:" + task_43_0)hashMapResult["cpuInfo_dict"] = str(cpuInfo[0])hashMapResult["memoryInfo_dict"] = str(memoryInfo[0])hashMapResult["diskinfo_dict"] = str(totalDisk)hashMapResult["isInternet_dict"] = task_43_0hashMapResult["grade_result7_43"] = 5# self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult7_43', json.dumps(hashMap)))# hashMap = {}# print()raid = getIsRaid()task_46_0 = "沒有主機磁盤raid"if (raid == 1):task_46_0 = "有主機磁盤raid"hashMapResult["raid_dict"] = task_46_0hashMapResult["raid"] = raidnicRedundancy = getIsNicRedundancy()task_46_1 = "沒有冗余"if (nicRedundancy == 1):task_46_1 = "網卡冗余"# print("任務46-->能采集主機磁盤(RAID)、網卡等關鍵部件冗余、雙機熱備(cluster集群)等硬件內容:" + "未知")# print("任務46-->網卡是否冗余:" + task_46_1)hashMapResult["nicRedundancy_dict"] = task_46_1hashMapResult["nicRedundancy"] = nicRedundancyhashMapResult["grade_result8_46"] = 5# print()# self.mainFrame.evaluateJavaScript('%s(%s)' % ('showResult8_46', json.dumps(hashMap)))# print(hashMapResult["NewAdministratorName"])# print(hashMapResult)#oneHundred()except Exception as e:# self.finished_signal.emit(0)pass# 設置表格樣式
def set_style(name, weight, color, bold=False):style = xlwt.XFStyle()font = xlwt.Font()# 設置字體類型font.name = name# 設置字體粗體# font.bold = bold# 設置字體顏色font.colour_index = colorfont._weight = weightstyle.font = fontreturn styledef get_desktop():key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, \r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders', )return winreg.QueryValueEx(key, "Desktop")[0]class viewsThread(threading.Thread):def __init__(self, threadID, name, counter):threading.Thread.__init__(self)self.threadID = threadIDself.name = nameself.counter = counterdef run(self): # 把要執行的代碼寫到run函數里面 線程在創建后會直接運行run函數app = QtGui.QApplication(sys.argv)demoWin = DemoWin()sys.exit(app.exec_())if __name__ == '__main__':buildWindowsSecurityPolicy()commonMap = buildCommonMap()securityPolicy = windowsSecurityPolicyToDict()windowsService = windowsServiceToDict()windowsProcess = windowsProcessToDict()# 創建新線程app = QtGui.QApplication(sys.argv)demoWin = DemoWin()sys.exit(app.exec_())# thread1 = DemoWinThread(1, "Thread-1", 1)# thread1.start()
https://pan.baidu.com/s/1Ftz2MDDFoLkxLyQx3Io2yQ
lcb5
總結
以上是生活随笔為你收集整理的服务器安全基线检查(Python)代码执行的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 眼下最流行的五大CSS框架,你都知道么?
- 下一篇: python微信加人_python模仿微