def __init__(self,useLogger=True): self.f = None self.writer = writer.writer() self.P = process.process(makeDirs=False) self.gU= graphUtils.graphUtils() self.pip= pipath.pipath() self.requestedRuns = 'ALL' self.now = now = datetime.datetime.now() self.start_time = now fmt = '%Y%m%d_%H%M%S_%f' cnow = now.strftime(fmt) self.parentDir = 'Second/'+cnow+'/' self.logdir = self.parentDir + 'Log/' self.figdir = self.parentDir + 'Figures/' dirs = self.pip.fix( [self.parentDir, self.logdir, self.figdir] ) # make paths platform indepedent for d in dirs: if os.path.isdir(d): pass else: try: os.mkdir(d) except IOError,e: print 'second__init__',e else: print 'second__init__ created',d
def __init__(self): #Eventually will init commands from file x self.logger = writer() self.currentMinute = 0 self.lastMinute = -1 self.quoteTime = datetime.datetime.now() - datetime.timedelta(seconds=10) self.modList = ['moomasterq']#as long as this isn't empty the bot will work
def parse(vmCodeString, filename): # read .vm file # vmCode = open(filename, 'r').read() # parse into array where each index is a line vmCode = vmCodeString.split('\n') # removes lines with comments and lines that contain nothing but whitespace vmCode = filter(lambda line: (not line.startswith('//')) and (not re.match('^\s*$', line)), vmCode) # removes comments after commands vmCode = map(lambda line: line.split('//', 1)[0], vmCode) # removes all whitespace from remaining lines # vmCode = map(lambda line: re.sub('\s+', '', line), vmCode) # Trim whitespace off edges of lines vmCode = map(lambda line: line.strip(), vmCode) # converts Virtual Machine instructions to Assembly # filename is used to push and pop static segment vmCode = map(lambda line: writer(line, os.path.basename(filename)), vmCode) # converts array of strings of assembly instructions into one long set of instructions vmCode = reduce(lambda commandList, allCommands: commandList + allCommands, vmCode) # converts string of commands to array where each item is a string that contains a single command vmCode = vmCode.split('\n') # last item is a blank string vmCode.pop() return vmCode
def processFiles(fileList): # read source to get message name list messageNameList = [] for xx in fileList: with open(xx, 'r') as sourceFile: name = '' attrs = [] for line in sourceFile.readlines(): x = re.match('message ', line) y = line.find('=') z = re.match('}', line) if x: name = line[x.end():] name = name[:name.find(' ')] attrs = [] if y > 0 and name != '': s = line.replace('\t', ' ') attr = filter(lambda x: x != '', s.split(' '))[2] attr = attr.strip() attrs.append(attr) if z and name != '': messageNameList.append((name, attrs, )) name = '' o = writer(os.path.join(rel_path_ouput, "proto_factory.py")) o.wl("import guard_proto_pb2") o.wl("from string_hash import StringHash") o.wl() o.wl("def create_pb(hash):", 4) for messageNameT in messageNameList: messageName = messageNameT[0] o.wl("if hash == StringHash.calculate_hash('" + messageName + "'):", 4) o.wl("return getattr(guard_proto_pb2, '" + messageName + "')()") o.wl("", -4) o.wl("return None") o.wl("", -4) o.wl("def get_pb_name(hash):", 4) for messageNameT in messageNameList: messageName = messageNameT[0] o.wl("if hash == StringHash.calculate_hash('" + messageName + "'):", 4) o.wl("return '" + messageName + "'") o.wl("", -4) o.wl("return None") o.wl("", -4) o.wl("def res(f, pb):", 4) o.wl("p = pb.__class__.__name__") for messageNameT in messageNameList: messageName = messageNameT[0] attrs = messageNameT[1] o.wl("if p == '" + messageName + "':", 4) o.wl("attrs = " + str(attrs)) o.wl("return f(pb, attrs)") o.wl("", -4) o.wl("return None") o.flush()
def run(options): output = writer(options) maxDepth = options.depth queue = deque([(options.target, 0)]) info = {} # contains all scraped info visited = [] # array of visited urls scraped = { # list of scraped elements; to avoid duplication 'a': [], 'img': [], } while queue: url, depth = queue.popleft() if depth > maxDepth: break if options.verbose == True: print str(depth) + " Visiting: " + url visited.append(url); info[url] = {} try: response = urllib2.urlopen(url) except urllib2.HTTPError as e: if options.verbose == True: print "({0}): {1}".format(e.errno, e.strerror) continue html = BeautifulSoup(response.read()) info[url]['src'] = html info[url]['a'] = html.find_all('a') info[url]['img'] = html.find_all('img') if options.extract == 'img': for image in info[url]['img']: href = fullPath(url, image['src']) if href != None and href not in scraped['img']: scraped['img'].append(href) output(href + '\n') for link in info[url]['a']: if not link.get('href'): continue href = fullPath(url, link.get('href')); if href == None: continue if options.extract == 'a': output(href + '\n') if href not in visited and href not in qtl(queue): queue.append((href, depth + 1));
def __init__(self,makeDirs=True): self.R = reader.reader() self.W = wfanal.wfanal() self.writer = writer.writer() self.cT = calibThermocouple.calibThermocouple() self.gU= graphUtils.graphUtils() self.pip= pipath.pipath() self.writeRecon = None self.overlaps = 0 self.lastEventDumped = None self.Hists = {} self.TDChistnames = {} self.refTDCs = ['S2','H0'] self.WFHists = [] self.Times = [] self.rawTemps = [] self.calTemps = [] self.AllTrigsfname = None self.rootpyEvts = None self.NoHists = False if makeDirs: now = datetime.datetime.now() self.start_time = now fmt = '%Y%m%d_%H%M%S_%f' cnow = now.strftime(fmt) parentDir = 'Results/'+cnow+'/' self.logdir = parentDir + 'Log/' self.figdir = parentDir + 'Figures/' self.WFfigdir = self.figdir + 'WF/' self.TDCfigdir= self.figdir + 'TDC/' self.outputdir= parentDir + 'Output/' # create list of platform-independent path dirs = self.pip.fix( [parentDir, self.logdir, self.figdir, self.WFfigdir, self.TDCfigdir, self.outputdir] ) parentDir, self.logdir, self.figdir, self.WFfigdir, self.TDCfigdir, self.outputdir = dirs for d in dirs: if os.path.isdir(d): pass else: try: os.makedirs(d) except IOError,e: print 'process__init__',e else: print 'process__init__ created',d
# If user closes GUI window, exit program if gui.output == None: sys.exit() # File containing raw data CSV_FILE = open(gui.output[0], 'r') # Directory of output file RUNSHEET_DIRECTORY_STR = gui.output[1] + "/" # Runsheet date DAY_OF_OPERATIONS = gui.output[2] # Shift sorter s = sorter.sorter(CSV_FILE) # Create and sort shifts list shifts = s.sort(s.createShifts(DAY_OF_OPERATIONS)) # Runsheet writer w = writer.writer() # Runsheet workbook w.makeWorkbook(shifts, RUNSHEET_DIRECTORY_STR) # Open generated runsheet if platform.system() == "Darwin": os.system("open " + '"' + RUNSHEET_DIRECTORY_STR + w.dateStrForFilename + ".xlsx" + '"') elif platform.system() == "Windows": os.system("start " + RUNSHEET_DIRECTORY_STR + w.dateStrForFilename + ".xlsx")
"""Wrapper for the writer application""" import sys sys.path.append('/var/www/wsgi-bin/datastore/writer') import writer configfile = '/var/www/wsgi-bin/datastore/examples/config.ini' writer.writer(configfile)
def persistence_info(log_file_path): ''' cf https://www.fuzzysecurity.com/tutorials/19.html **FR** Chercher les élements persistants dans : - les répertoires de démarrage - Regedit **EN** Search for persistent objects in : - Startup directories - Regedit ''' writer.writer('Search for persistent objects') # 1 - Ecriture début de log log_file = log_file_path + "FINAL.html" writer.writelog(log_file, '<div><br>\n') elem = '<h2>Informations about persistent objects of computer "' + COMPUTERNAME + '"</h2>' writer.prepa_log_scan(log_file, elem) # 2 - obtenir les objets persistants # 2.1a - startup dirs drive = os.environ['SYSTEMDRIVE'] user = os.environ['USERNAME'] dir_list = [drive + '/Users/' + user + '/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup', drive + '/ProgramData/Microsoft/Windows/Start Menu/Programs/Startup', drive + '/Documents and Settings/All Users/Start Menu/Programs/Startup'] files_list = [] for dirs in dir_list: if os.path.isdir(dirs): files_list = get_files(dirs, files_list) # 2.1b - Ecriture dans le log writer.writelog(log_file, 'Persistent objects in startup dirs :<br>\n') for elem in files_list: writer.writelog(log_file, elem + '<br>\n') # 2.2a - regedit hive_list = {'HKEY_LOCAL_MACHINE': winreg.HKEY_LOCAL_MACHINE, 'HKEY_CURRENT_USER':winreg.HKEY_CURRENT_USER} reg_list = [r'Software\Microsoft\Windows\CurrentVersion\Run', r'Software\Microsoft\Windows\CurrentVersion\RunOnce', r'Software\Microsoft\Windows\CurrentVersion\RunServices', r'Software\Microsoft\Windows\CurrentVersion\RunServicesOnce', r'Software\Microsoft\Windows NT\CurrentVersion\Winlogon'] per_reg_dict = {} for hkeyname, hkeyvalue in hive_list.items(): for key in reg_list: fullhkeyreg = hkeyname + '\\' + key tosave_dict = search_reg(hkeyvalue, key) if tosave_dict: for name, value in tosave_dict.items(): per_reg_dict[fullhkeyreg + '_' + name] = {'regkey':fullhkeyreg, 'name':name, 'value':value} # 2.2b - Ecriture du fichier CSV header = ['regkey', 'name', 'value'] csv_file = log_file_path + "persistants_reg.csv" writer.write_csv(csv_file, header, per_reg_dict) # 2.2c - Transformation du CSV en HTML htmltxt = writer.csv2html(csv_file, 'Persistent reg objects') # 2.2d - Ecriture de la fin du log writer.writelog(log_file, '<br>\nPersistent reg objects :<br>\n') writer.writelog(log_file, htmltxt) # 3 - Ecriture de la fin du log writer.writelog(log_file, '\n</div>\n') return log_file
def compile(self): self.playbook_name = writer.writer(self, self.playbook_name)
def security_product_info(log_file_path): ''' http://neophob.com/2010/03/wmi-query-windows-securitycenter2/ **FR** Scan le système pour obtenir la liste et le status des produits de sécurité (antivirus, parefeu, antispyware) Retourne le dictionnaire des produits de sécurité **EN** Scan to get security product in the system with their status (antivirus, firewall, antispyware) Return security products dict ''' # Determinate what namespace to call sec_name_space = 'SecurityCenter' if detect_os() != 'xp': sec_name_space = 'SecurityCenter2' str_computer = '.' obj_wmi_service = win32com.client.Dispatch('WbemScripting.SWbemLocator') obj_sw_bem_services = obj_wmi_service.ConnectServer(str_computer, 'root\\' + sec_name_space) writer.writer('Getting security products') # 1 - Ecriture début de log log_file = log_file_path + "FINAL.html" writer.writelog(log_file, '<div><br>\n') elem = '<h2>Security products on computer "' + COMPUTERNAME + '"</h2>' writer.prepa_log_scan(log_file, elem) # 2 - Obtention des informations security_product_dict = {} i = 1 # Antivirus col_items = obj_sw_bem_services.ExecQuery("select * from AntivirusProduct") i, security_product_dict = security_product_get(i, security_product_dict, col_items, 'Antivirus') # Firewalls # Windows xpfw = win32com.client.gencache.EnsureDispatch('HNetCfg.FwMgr', 0) xpfw_policy = xpfw.LocalPolicy.CurrentProfile writer.writelog(log_file, 'Windows firewall enabled : ' + str(xpfw_policy.FirewallEnabled) + '<br>\n') # Third party firewall col_items = obj_sw_bem_services.ExecQuery("select * from FireWallProduct") i, security_product_dict = security_product_get(i, security_product_dict, col_items, 'Firewall') if detect_os() != 'xp': # AntiSpyware col_items = obj_sw_bem_services.ExecQuery("select * from AntiSpywareProduct") i, security_product_dict = security_product_get(i, security_product_dict, col_items, 'Antispyware') # 3 - Ecrire du fichier CSV header = ['Type', 'Name', 'GUID', 'pathProduct', 'pathReporting', 'productState', 'rtstatus', 'defstatus'] csv_file = log_file_path + "security_products.csv" writer.write_csv(csv_file, header, security_product_dict) # 4 - Transformation du CSV en HTML htmltxt = writer.csv2html(csv_file, 'Security Products') htmltxt = htmltxt.replace('<TD>Outdated</TD>', '<TD id="ko">Outdated</TD>') htmltxt = htmltxt.replace('<TD>Up to date</TD>', '<TD id="ok">Up to date</TD>') htmltxt = htmltxt.replace('<TD>Disabled</TD>', '<TD id="ko">Disabled</TD>') htmltxt = htmltxt.replace('<TD>Enabled</TD>', '<TD id="ok">Enabled</TD>') # 5 - Ecriture de la fin du log writer.writelog(log_file, str(len(security_product_dict)) + ' security products :\n') writer.writelog(log_file, htmltxt) writer.writelog(log_file, '\n</div>\n') return security_product_dict
def system_info(log_file_path): ''' ~ systeminfo | find /V /I "hotfix" | find /V "KB" ~ wmic logicaldisk get volumename, description, FileSystem, Caption, ProviderName **FR** Scan le système (os, bios, cpu, ram, cartes réseaux, disques durs, etc) Retourne le log généré **EN** Scan system (os, bios, cpu, ram, network interfaces, drives, etc) Return generated log ''' writer.writer('Getting system informations') delimiter = '*' * 40 # 1 - Ecriture début de log log_file = log_file_path + "FINAL.html" writer.writelog(log_file, '<div><br>\n') elem = '<h2>System information of computer "' + COMPUTERNAME + '"</h2>' writer.prepa_log_scan(log_file, elem) # 2 - Get information from regedit hive = winreg.HKEY_LOCAL_MACHINE key = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion" # W7-64/32 registry_key = winreg.OpenKey(hive, key, 0, winreg.KEY_READ | winreg.KEY_WOW64_64KEY) # W7-64/32 # 2' - Specific to W10 (ok for 64 bits) if detect_os() == '10': writer.writer('Perform operations for W10+ OS') key = r"SYSTEM\Setup" #\Source OS" #W10 registry_keys = winreg.OpenKey(hive, key, 0, winreg.KEY_READ) i = 0 while 1: try: name = winreg.EnumKey(registry_keys, i) # print(name) if 'Source OS' in name: # print(name) key = key + '\\' + name registry_key = winreg.OpenKey(hive, key, 0, winreg.KEY_READ) #W10-64 break except Exception: break i += 1 # Continuing tosave_dict = {'InstallDate':'N/A', 'SystemRoot':'N/A', 'ProductId':'N/A', 'ProductName':'N/A', 'RegisteredOrganization':'N/A', 'RegisteredOwner':'N/A'} to_get_list = ['InstallDate', 'SystemRoot', 'ProductId', 'ProductName', 'RegisteredOrganization', 'RegisteredOwner'] i = 0 while 1: try: name, value, _ = winreg.EnumValue(registry_key, i) if name in to_get_list: # print(repr(name), value) tosave_dict[name] = value except Exception: # print('error : ' + name) break i += 1 # print(tosave_dict) # OS writer.writelog(log_file, 'Hostname : ' + platform.node() + '<br>\n') # print('OS : ' + platform.system() + ' ' + platform.version()) writer.writelog(log_file, 'OS : ' + tosave_dict.get('ProductName') + '<br>\n') writer.writelog(log_file, 'OS type : ' + platform.machine() + '<br>\n') writer.writelog(log_file, 'Product Id : ' + tosave_dict.get('ProductId') + '<br>\n') writer.writelog(log_file, 'Install Date: ' + str(datetime.fromtimestamp(tosave_dict.get('InstallDate'))) + '<br>\n') writer.writelog(log_file, 'System Root: ' + tosave_dict.get('SystemRoot') + '<br>\n') # Language (Windows Vista or further) if detect_os() != 'xp': buf_size = 32 buf = ctypes.create_unicode_buffer(buf_size) dw_flags = 0 lcid = ctypes.windll.kernel32.GetUserDefaultUILanguage() ctypes.windll.kernel32.LCIDToLocaleName(lcid, buf, buf_size, dw_flags) writer.writelog(log_file, 'Regional and language options : ' + buf.value + '<br>\n') # Time zone writer.writelog(log_file, 'Time zone : ' + time.tzname[0] + '<br>\n') writer.writelog(log_file, delimiter + '<br>\n') # Owner writer.writelog(log_file, 'Registered Organization : ' + tosave_dict.get('RegisteredOrganization') + '<br>\n') writer.writelog(log_file, 'Registered Owner : ' + tosave_dict.get('RegisteredOwner') + '<br>\n') writer.writelog(log_file, delimiter + '<br>\n') # Computer model/brand str_computer = '.' obj_wmi_service = win32com.client.Dispatch('WbemScripting.SWbemLocator') obj_sw_bem_services = obj_wmi_service.ConnectServer(str_computer, 'root\\cimv2') col_items = obj_sw_bem_services.ExecQuery('SELECT * FROM Win32_ComputerSystem') for obj_item in col_items: writer.writelog(log_file, 'Manufacturer : ' + obj_item.Manufacturer + '<br>\n') try: writer.writelog(log_file, 'SystemFamily : ' + obj_item.SystemFamily + '<br>\n') except AttributeError: writer.writelog(log_file, 'SystemFamily : N/A<br>\n') writer.writelog(log_file, 'Model : ' + obj_item.Model + '<br>\n') writer.writelog(log_file, 'Type : ' + obj_item.SystemType + '<br>\n') writer.writelog(log_file, delimiter + '<br>\n') # Processor col_items = obj_sw_bem_services.ExecQuery('Select * from Win32_Processor') for obj_item in col_items: writer.writelog(log_file, 'Processor : ' + obj_item.Name + '<br>\n') writer.writelog(log_file, 'Core : ' + str(obj_item.NumberOfCores) + '<br>\n') writer.writelog(log_file, 'Logical core : ' + str(obj_item.NumberOfLogicalProcessors) + '<br>\n') try: writer.writelog(log_file, 'Virtualization enabled : ' + str(obj_item.VirtualizationFirmwareEnabled) + '<br>\n') except AttributeError: writer.writelog(log_file, 'Virtualization enabled : N/A<br>\n') writer.writelog(log_file, delimiter + '<br>\n') # Bios col_items = obj_sw_bem_services.ExecQuery("SELECT * FROM Win32_BIOS") for obj_item in col_items: writer.writelog(log_file, "BIOS Version : " + str(obj_item.BIOSVersion) + '<br>\n') writer.writelog(log_file, "Release Date : " + str(datetime.strptime(str(obj_item.ReleaseDate[:8]), "%Y%m%d").strftime("%Y-%m-%d")) + '<br>\n') writer.writelog(log_file, delimiter + '<br>\n') # Memory mem = psutil.virtual_memory() writer.writelog(log_file, 'Total memory : ' + str(mem.total >> 20) + ' Mo<br>\n') writer.writelog(log_file, 'Available memory : ' + str(mem.available >> 20) + ' Mo<br>\n') writer.writelog(log_file, 'Used memory : ' + str(mem.used >> 20) + ' Mo (' + str(mem.percent) + ' %)<br>\n') writer.writelog(log_file, 'Free memory : ' + str(mem.free >> 20) + ' Mo<br>\n') writer.writelog(log_file, delimiter + '<br>\n') # Domaine writer.writelog(log_file, 'Domain : ' + os.environ['userdomain'] + '<br>\n') writer.writelog(log_file, delimiter + '<br>\n') # Network interfaces str_computer = '.' obj_wmi_service = win32com.client.Dispatch('WbemScripting.SWbemLocator') obj_sw_bem_services = obj_wmi_service.ConnectServer(str_computer, 'root\\cimv2') col_items = obj_sw_bem_services.ExecQuery('select * from Win32_NetworkAdapterConfiguration') network_dict = {} for obj_item in col_items: if obj_item.MACAddress is not None: net_caption = re.findall("] (.*)", obj_item.Caption)[0] # print(net_caption, obj_item.IPAddress) try: dns_srv = '<br>'.join(obj_item.DNSServerSearchOrder) except TypeError: dns_srv = obj_item.DNSServerSearchOrder try: ipv4 = obj_item.IPAddress[0] except IndexError: ipv4 = '' except TypeError: ipv4 = '' try: ipv6 = obj_item.IPAddress[1] except IndexError: ipv6 = '' except TypeError: ipv6 = '' try: dgw = ''.join(obj_item.DefaultIPGateway) except TypeError: dgw = obj_item.DefaultIPGateway try: dhcp_srv = ''.join(obj_item.DHCPServer) except TypeError: dhcp_srv = obj_item.DHCPServer network_dict[net_caption] = {'Name':net_caption, 'MAC':obj_item.MACAddress, 'Enabled':obj_item.IPEnabled, 'IpV4':ipv4, 'IpV6':ipv6, 'Default Gateway':dgw, 'DHCP Enabled':obj_item.DHCPEnabled, 'DHCP Server':dhcp_srv, 'WINS Primary Server':obj_item.WINSPrimaryServer, 'WINS Secondary Server':obj_item.WINSSecondaryServer, 'DNS Domain':obj_item.DNSDomain, 'DNS Servers':dns_srv} writer.writelog(log_file, str(len(network_dict)) + ' network interfaces found :<br>\n') # Ecriture du fichier CSV header = ['Name', 'MAC', 'Enabled', 'IpV4', 'IpV6', 'Default Gateway', 'DHCP Enabled', 'DHCP Server', 'WINS Primary Server', 'WINS Secondary Server', 'DNS Domain', 'DNS Servers'] csv_file = log_file_path + "networkInterfaces.csv" writer.write_csv(csv_file, header, network_dict) # Transformation du CSV en HTML htmltxt = writer.csv2html(csv_file, 'Network Interfaces') # Ecriture sur le log writer.writelog(log_file, htmltxt) writer.writelog(log_file, delimiter + '<br>\n') # Drives drives = psutil.disk_partitions() drives_dict = {} for drive in drives: drive_path = re.findall("device='(.*?)'", str(drive))[0] if drive.opts != 'cdrom': try: disk_usage = psutil.disk_usage(drive_path) drives_dict[str(drive_path)] = {'Path':str(drive_path), 'Total_Space (Go)':str(disk_usage.total >> 30), 'Free_Space (Go)':str(disk_usage.free >> 30), 'Used_space (Go)':str(disk_usage.used >> 30), 'Used_space (%)':str(disk_usage.percent)} except Exception: pass # Ecriture du fichier CSV header = ['Path', 'Total_Space (Go)', 'Free_Space (Go)', 'Used_space (Go)', 'Used_space (%)'] csv_file = log_file_path + "drives.csv" writer.write_csv(csv_file, header, drives_dict) # Transformation du CSV en HTML htmltxt = writer.csv2html(csv_file, 'Drives') # Ecriture sur le log writer.writelog(log_file, str(len(drives_dict)) + ' drive(s) found :<br>\n') writer.writelog(log_file, htmltxt) writer.writelog(log_file, delimiter + '<br>\n') # 3 - Ecriture fin de log writer.writelog(log_file, '\n</div>\n') return log_file
def user_info(log_file_path): ''' ~ net user <username> /domain & net user <username> **FR** Obtient la liste des utilisateurs AD et locaux de l'ordinateur avec la base de registre et WinNT Retourne le log généré **EN** Get AD and local users list of the computer with regedit and WinNT Return generated log ''' writer.writer('Getting computer users') hive = winreg.HKEY_LOCAL_MACHINE key_user = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" # AD users registry_key = None temp_user_list = [] temp2_user_list = [] profil_path = "ProfileImagePath" # 1 - Liste tous les profils try: registry_key = winreg.OpenKey(hive, key_user, 0, winreg.KEY_READ) # print("ok") except FileNotFoundError: # print("oups") pass # print(registry_key) if registry_key is not None: i = 0 while True: try: temp_user_list.append(winreg.EnumKey(registry_key, i)) # ok pour 1 clé i += 1 # print("value :", str(registry_key)) except Exception: # print(Exception) winreg.CloseKey(registry_key) break # 2 - Tri de la liste pour ne garder que les SID commençant par "1-5-21" et récupérer le nom des utilisateurs for item in temp_user_list: if "1-5-21" in item: # print(item) key = key_user + '\\' + item # print(key) try: registry_key = winreg.OpenKey(hive, key, 0, winreg.KEY_READ) value, _ = winreg.QueryValueEx(registry_key, profil_path) winreg.CloseKey(registry_key) # print(value) value_mod = re.findall(r'[^\\]+\s*$', value) # print(type(value_mod[0])) temp2_user_list.append(value_mod[0]) except FileNotFoundError: # print("oups") pass domain = os.environ['userdomain'] # 3 - Ecriture début de log log_file = log_file_path + "FINAL.html" writer.writelog(log_file, '<div><br>\n') elem = '<h2>Getting details about the ' + str(len(temp2_user_list)) + ' user(s) of computer "' + COMPUTERNAME + '"</h2>' elem2 = "<br>Domain : " + str(domain) + '\n' writer.prepa_log_scan(log_file, elem) writer.writelog(log_file, elem2) # 4 - Détails sur les utilisateurs user_dict = {} for user in temp2_user_list: try: obj_ou = win32com.client.GetObject("WinNT://" + domain + "/" + user + ",user") #User account fullname = str(obj_ou.Get('fullname')) # print(fullname) try: expiration_date = str(obj_ou.Get('AccountExpirationDate')) except Exception: expiration_date = 'N/A' profile = str(obj_ou.Get('Profile')) login_script = str(obj_ou.Get('LoginScript')) try: last_login = str(obj_ou.Get('lastlogin')) except com_error: last_login = '******' primary_gid = str(obj_ou.Get('PrimaryGroupID')) auto_unlock_interval = str(obj_ou.Get('AutoUnlockInterval')) lockout_observation_interval = str(obj_ou.Get('LockoutObservationInterval')) homedir = str(obj_ou.Get('HomeDirectory')) homedir_drive = str(obj_ou.Get('HomeDirDrive')) #Password pwd_age = str(round(obj_ou.Get('PasswordAge')/3600/24)) pwd_min_age = str(round(obj_ou.Get('MinPasswordAge')/3600/24)) pwd_max_age = str(round(obj_ou.Get('MaxPasswordAge')/3600/24)) pwd_expired = str(obj_ou.Get('PasswordExpired')) pwd_max_bad_pwd_allowed = str(obj_ou.Get('MaxBadPasswordsAllowed')) pwd_min_length = str(obj_ou.Get('MinPasswordLength')) pwd_history_length = str(obj_ou.Get('PasswordHistoryLength')) #Groups groups_list = [] for grp in obj_ou.Groups(): groups_list.append(grp.Name + '<br>') #Flag flag_final_list = [] flag = obj_ou.Get('UserFlags') #Get flags with user flag (user flag = sum(flags)) flag_list = [] mini, flag_to_save = calc_flag(flag) flag_list.append(flag_to_save) while mini != 0: mini, flag_to_save = calc_flag(mini) flag_list.append(flag_to_save) #Verify if flag = sum(flag_list) if flag == sum(flag_list): flag_final_list.append(str(flag) + ' => ' + str(flag_list) + '<br>') #Get flags description with flag nums saved flag_final_list.append('Flag properties :') for k, value in USER_FLAGS_DICT.items(): if value in flag_list: flag_final_list.append('<br>' + str(value) + ' : ' + str(k)) user_dict[user] = {'User':user, 'Fullname':fullname, 'Expiration_Date':expiration_date, 'Profile':profile, 'Login_Script':login_script, 'Last_Login':last_login, 'Primary_Group_ID':primary_gid, 'Auto_Unlock_Interval (secs)': auto_unlock_interval, 'Lockout_Observation_Interval (secs)':lockout_observation_interval, 'HomeDir':homedir, 'HomeDirDrive':homedir_drive, 'pwd_age (days)':pwd_age, 'pwd_min_age (days)':pwd_min_age, 'pwd_max_age (days)':pwd_max_age, 'pwd_expired':pwd_expired, 'pwd_max_bad_pwd_allowed':pwd_max_bad_pwd_allowed, 'pwd_min_length':pwd_min_length, 'pwd_history_length':pwd_history_length, 'Groups':(''.join(groups_list)), 'Flag':(''.join(flag_final_list))} except Exception: pass i += 1 if user_dict != '': # Ecriture du fichier CSV header = ['User', 'Fullname', 'Expiration_Date', 'Profile', 'Login_Script', 'Last_Login', 'Primary_Group_ID', 'Auto_Unlock_Interval (secs)', 'Lockout_Observation_Interval (secs)', 'HomeDir', 'HomeDirDrive', 'pwd_age (days)', 'pwd_min_age (days)', 'pwd_max_age (days)', 'pwd_expired', 'pwd_max_bad_pwd_allowed', 'pwd_min_length', 'pwd_history_length', 'Groups', 'Flag'] csv_file = log_file_path + "users.csv" writer.write_csv(csv_file, header, user_dict) # Transformation du CSV en HTML htmltxt = writer.csv2html(csv_file, 'Users details') writer.writelog(log_file, htmltxt) # 5 - Ecriture de la fin du log writer.writelog(log_file, '\n</div>\n') return log_file
#----------------------------------------------------------------------- page = 1 while page != explore + 1: print() print('Page {}...'.format(page)) print('-' * 80) soup = BeautifulSoup(requests.get(url, headers=headers).content, 'html.parser') search_div = soup.find_all(class_='rc') # find all divs that contains search result titles, links, descriptions = functions.get_result(search_div, titles, links, descriptions) next_link = soup.select_one('a:contains("Next")') if not next_link: break url = 'https://google.com' + next_link['href'] page += 1 #----------------------------------------------------------------------- writer.writer(titles,links,cont,config) #writes to file fileWordCount.get_count(cont)
def custom_writer(iterable_object, filename): from writer import writer writer(iterable_object, filename)