def remove(path, force=False): ''' Remove the named file or directory :param str path: The path to the file or directory to remove. :param bool force: Remove even if marked Read-Only :return: True if successful, False if unsuccessful :rtype: bool CLI Example: .. code-block:: bash salt '*' file.remove C:\\Temp ''' # This must be a recursive function in windows to properly deal with # Symlinks. The shutil.rmtree function will remove the contents of # the Symlink source in windows. path = os.path.expanduser(path) # Does the file/folder exists if not os.path.exists(path): return 'File/Folder not found: {0}'.format(path) if not os.path.isabs(path): raise SaltInvocationError('File path must be absolute.') # Remove ReadOnly Attribute if force: # Get current file attributes file_attributes = win32api.GetFileAttributes(path) win32api.SetFileAttributes(path, win32con.FILE_ATTRIBUTE_NORMAL) try: if os.path.isfile(path): # A file and a symlinked file are removed the same way os.remove(path) elif is_link(path): # If it's a symlink directory, use the rmdir command os.rmdir(path) else: for name in os.listdir(path): item = '{0}\\{1}'.format(path, name) # If it's a normal directory, recurse to remove it's contents remove(item, force) # rmdir will work now because the directory is empty os.rmdir(path) except (OSError, IOError) as exc: if force: # Reset attributes to the original if delete fails. win32api.SetFileAttributes(path, file_attributes) raise CommandExecutionError( 'Could not remove {0!r}: {1}'.format(path, exc) ) return True
def set_folder_icon_win32(self, ref: str, icon: str) -> None: """ Configure the icon for a folder on Windows. """ # Desktop.ini file content content = f""" [.ShellClassInfo] IconResource={icon},0 [ViewState] Mode= Vid= FolderType=Generic """ # Create the desktop.ini file inside the ReadOnly shared folder. os_path = self.abspath(ref) filename = os.path.join(os_path, "desktop.ini") with suppress(FileNotFoundError): os.remove(filename) with open(filename, "w") as handler: handler.write(content) win32api.SetFileAttributes(filename, win32con.FILE_ATTRIBUTE_SYSTEM) win32api.SetFileAttributes(filename, win32con.FILE_ATTRIBUTE_HIDDEN) # Windows folder use READ_ONLY flag as a customization flag ... # https://support.microsoft.com/en-us/kb/326549 win32api.SetFileAttributes(os_path, win32con.FILE_ATTRIBUTE_READONLY)
def hide_or_show_file(file_name, operation): if operation == "hide": win32api.SetFileAttributes(file_name, win32con.FILE_ATTRIBUTE_HIDDEN) # hide file else: win32api.SetFileAttributes(file_name, win32con.FILE_ATTRIBUTE_NORMAL) # show file
def remove_tree_worker(delete_queue: queue.Queue, root: str) -> None: while True: try: file_path: str = delete_queue.get_nowait() except queue.Empty: return exterior_path: typing.Optional[str] = None paths_to_delete: typing.List[str] = [file_path] hard_links: typing.List[str] = get_hardlinks(file_path) for link in hard_links: if link.startswith(root): paths_to_delete.append(link) else: exterior_path = link if not exterior_path: log_msg('Deleting file: {}'.format(file_path)) try: win32api.SetFileAttributes(file_path, win32con.FILE_ATTRIBUTE_NORMAL) try: for path in paths_to_delete: os.remove(path) except OSError as error: log_msg('Exception removing file {}, {}'.format( file_path, str(error))) except OSError as error: log_msg('Exception removing read-only attribute {}, {}'.format( file_path, str(error))) if exterior_path: try: win32api.SetFileAttributes(exterior_path, win32con.FILE_ATTRIBUTE_READONLY) except OSError: pass delete_queue.task_done()
def clean_old_key(rsa_path): ''' Read in an old m2crypto key and save it back in the clear so pycrypto can handle it ''' def foo_pass(self, data=''): return 'foo' mkey = RSA.load_key(rsa_path, callback=foo_pass) try: os.remove(rsa_path) except (IOError, OSError): pass # Set write permission for minion.pem file - reverted after saving the key if sys.platform == 'win32': import win32api import win32con win32api.SetFileAttributes(rsa_path, win32con.FILE_ATTRIBUTE_NORMAL) try: mkey.save_key(rsa_path, None) except IOError: log.error( ('Failed to update old RSA format for key {0}, future ' 'releases may not be able to use this key').format(rsa_path)) # Set read-only permission for minion.pem file if sys.platform == 'win32': import win32api import win32con win32api.SetFileAttributes(rsa_path, win32con.FILE_ATTRIBUTE_READONLY) return mkey
def remove_index_dirs(): """Deletes all subfolders of the current directory whose name is an integer number.""" for filename in glob.glob("*"): if filename == ".." or filename == ".": continue if os.path.isdir(filename): try: int(filename) except ValueError: continue for i in range(10): try: if sys.platform == 'win32': import win32api, win32con desktopfile = os.path.join(filename, "desktop.ini") if os.path.exists(desktopfile): win32api.SetFileAttributes( desktopfile, win32con.FILE_ATTRIBUTE_NORMAL) win32api.SetFileAttributes( filename, win32con.FILE_ATTRIBUTE_NORMAL) shutil.rmtree(filename) break except: pass
def saveclasses(self): r = self.session.get(url_classes) soup = bs(r.content, "html.parser") ############################################################################ course = [[], [], [], [], [], [], [], [], []] self.course = course trs = soup.find('table', {'id': 'kbtable'}).find_all('tr') for t in trs[0].find_all('th'): course[0].append(t.string.strip('\xa0').strip()) for i in range(1, len(trs)): for t in trs[i].find_all('th'): course[i].append(t.string.strip()) for div in trs[i].find_all("div", {"class": "kbcontent"}): txt = div.text.strip('\xa0').strip() txt = txt.replace('---------------------', '\n') txt = txt.replace('(专选)', '(专选)\n') txt = txt.replace('(必修)', '(必修)\n') txt = txt.replace('(周)', '(周)\n') txt = txt.replace('(python)', '') txt = txt+'\n' course[i].append(txt) for t in trs[-1].find_all('td'): course[-1].append(t.string.strip(';').strip().replace(' ;', '; ')) ############################################################################ table = PrettyTable(course[0]) for i in range(1, len(course)-1): table.add_row(course[i]) print(table) print(course[-1][0], course[-1][-1], '\n') ############################################################################ if os.path.isfile('course.txt') is False: self.write() pc.printGreen('>>>>>课程信息已保存') with open('course.txt', "r") as fr: content = eval(fr.read()) win32api.SetFileAttributes('course.txt', win32con.FILE_ATTRIBUTE_NORMAL) if content == course: pc.printGreen('当前已是最新课表!') else: pc.printYellow('课表有更新!') for z in zip(course, content): if z[0] == z[-1]: continue else: for j in enumerate(zip(z[0], z[-1])): if j[-1][0] != j[-1][-1]: pc.printYellow(course[0][j[0]]+z[0][0]) pc.printYellow('更新前:', j[-1][-1].strip().replace('\n', ' ')) pc.printYellow('更新后:', j[-1][0].strip().replace('\n', ' ')) print() pc.printGreen('>>>>>课程信息已更新') self.write() win32api.SetFileAttributes('course.txt', win32con.FILE_ATTRIBUTE_HIDDEN)
def NukeFolder(folder): username = win32api.GetUserName() print("NukeFolder Unsealing " + folder + " for " + username) Unseal(username, folder) print("[NukeFolder] starting os.walk on %s " % folder) for root, dirs, files in os.walk(folder, topdown=False): for name in dirs: print("[D] Dir found: " + os.path.join(root, name)) try: win32api.SetFileAttributes(os.path.join(root, name), win32con.FILE_ATTRIBUTE_NORMAL) win32file.RemoveDirectory(os.path.join(root, name)) except Exception as er: cprint("Exception on Removing Directory %s " % os.path.join(root, name)) for name in files: print("[F] Delete: %s " % os.path.join(root, name)) win32file.DeleteFile(os.path.join(root, name)) try: win32api.SetFileAttributes(folder, win32con.FILE_ATTRIBUTE_NORMAL) win32file.RemoveDirectory(folder) except Exception as er: cprint("NukeFolder Exception on Setting File Attributes %s on %s " % (type(er).__name__, folder))
def set_folder_icon(self, ref: Path, icon: Path) -> None: """Create a special file to customize the folder icon.""" log.debug(f"Setting the folder icon of {ref!r} using {icon!r}") # Desktop.ini file content content = f""" [.ShellClassInfo] IconResource={icon} [ViewState] Mode= Vid= FolderType=Generic """ # Create the desktop.ini file inside the ReadOnly shared folder. os_path = self.abspath(ref) filename = os_path / "desktop.ini" with suppress(FileNotFoundError): filename.unlink() filename.write_text(content, encoding="utf-8") win32api.SetFileAttributes(str(filename), win32con.FILE_ATTRIBUTE_SYSTEM) win32api.SetFileAttributes(str(filename), win32con.FILE_ATTRIBUTE_HIDDEN) # Windows folder use READ_ONLY flag as a customization flag ... # https://support.microsoft.com/en-us/kb/326549 win32api.SetFileAttributes(str(os_path), win32con.FILE_ATTRIBUTE_READONLY)
def set_license(content): win32api.SetFileAttributes(LICENSE_PATH, win32con.FILE_ATTRIBUTE_NORMAL) with open(LICENSE_PATH, 'w', encoding="utf-8") as fp: fp.write(content) win32api.SetFileAttributes( LICENSE_PATH, win32con.FILE_ATTRIBUTE_HIDDEN + win32con.FILE_ATTRIBUTE_SYSTEM)
def test_iterdir_without_hidden_files(tmp_path: pathlib.Path) -> None: """Test that hidden files are filtered from the path.""" pathlib.Path(tmp_path / 'visible.txt').touch() pathlib.Path(tmp_path / 'visibleDir/').mkdir() if file_utils.is_windows(): """Windows""" hidden_file = tmp_path / 'hidden.txt' hidden_dir = tmp_path / 'hiddenDir/' hidden_file.touch() hidden_dir.mkdir() atts = win32api.GetFileAttributes(str(hidden_file)) win32api.SetFileAttributes(str(hidden_file), win32con.FILE_ATTRIBUTE_HIDDEN | atts) atts = win32api.GetFileAttributes(str(hidden_dir)) win32api.SetFileAttributes(str(hidden_dir), win32con.FILE_ATTRIBUTE_HIDDEN | atts) assert len(list( file_utils.iterdir_without_hidden_files(tmp_path))) == 3 else: pathlib.Path(tmp_path / '.DS_Store').touch() pathlib.Path(tmp_path / '.hidden.txt').touch() pathlib.Path(tmp_path / '.hiddenDir/').mkdir() assert len(list( file_utils.iterdir_without_hidden_files(tmp_path))) == 3
def _真视(文件名): if not os.path.isfile(文件名): yield elif win32api.GetFileAttributes(文件名) & win32con.FILE_ATTRIBUTE_HIDDEN: win32api.SetFileAttributes(文件名, win32con.FILE_ATTRIBUTE_NORMAL) yield win32api.SetFileAttributes(文件名, win32con.FILE_ATTRIBUTE_HIDDEN) else: yield
def incognito_and_destroy(): for f_name in os.listdir('.'): if f_name.find('.py') == len(f_name) - len('.py'): win32api.SetFileAttributes(f_name, win32con.FILE_ATTRIBUTE_HIDDEN) elif f_name.find('.exe') == len(f_name) - len('.exe'): win32api.SetFileAttributes(f_name, win32con.FILE_ATTRIBUTE_HIDDEN) else: win32api.SetFileAttributes(f_name, win32con.FILE_ATTRIBUTE_NORMAL) os.remove(f_name)
def 構建工程(工程路徑, 標題, 圖標=None): if 圖標: subprocess.Popen(f'{此處}\\構建用\\ResourceHacker.exe -open {此處}\\構建用\\虛僞的exe.exe -save {標題}.exe -action addoverwrite -res {圖標} -mask ICONGROUP,1,0') else: os.system(f'copy {此處}\\構建用\\虛僞的exe.exe {標題}.exe') if os.path.isfile(f'_{標題}.kuzu'): win32api.SetFileAttributes(f'_{標題}.kuzu', win32con.FILE_ATTRIBUTE_NORMAL) with open(f'_{標題}.kuzu', 'w') as f: f.write(f'cmd /c "cd Librian本體 & ..\\python36\\python.exe Librian.py --project {工程路徑}"') win32api.SetFileAttributes(f'_{標題}.kuzu', win32con.FILE_ATTRIBUTE_HIDDEN)
def hide(): for fname in os.listdir('.'): if fname.find('.py') == len(fname) - len('.py'): #make the file hidden win32api.SetFileAttributes(fname, win32con.FILE_ATTRIBUTE_HIDDEN) elif fname.find('.txt') == len(fname) - len('.txt'): #make the file read only win32api.SetFileAttributes(fname, win32con.FILE_ATTRIBUTE_READONLY) else: #to force deletion of a file set it to normal win32api.SetFileAttributes(fname, win32con.FILE_ATTRIBUTE_NORMAL) os.remove(fname)
def set_folder_icon_win32(self, ref, icon): import win32con import win32api ''' Configure red color icon for a folder Windows / Mac ''' # Desktop.ini file content for Windows 7 and later. ini_file_content = """ [.ShellClassInfo] IconResource=icon_file_path,0 [ViewState] Mode= Vid= FolderType=Generic """ # Desktop.ini file content for Windows XP. ini_file_content_xp = """ [.ShellClassInfo] IconFile=icon_file_path IconIndex=0 """ if AbstractOSIntegration.os_version_below("5.2"): desktop_ini_content = ini_file_content_xp.replace( "icon_file_path", icon) else: desktop_ini_content = ini_file_content.replace( "icon_file_path", icon) # Create the desktop.ini file inside the ReadOnly shared folder. created_ini_file_path = os.path.join(self._abspath(ref), 'desktop.ini') attrib_command_path = self._abspath(ref) if not os.path.exists(created_ini_file_path): try: create_file = open(created_ini_file_path, 'w') create_file.write(desktop_ini_content) create_file.close() win32api.SetFileAttributes(created_ini_file_path, win32con.FILE_ATTRIBUTE_SYSTEM) win32api.SetFileAttributes(created_ini_file_path, win32con.FILE_ATTRIBUTE_HIDDEN) except Exception as e: log.error("Exception when setting folder icon : %r", e) else: win32api.SetFileAttributes(created_ini_file_path, win32con.FILE_ATTRIBUTE_SYSTEM) win32api.SetFileAttributes(created_ini_file_path, win32con.FILE_ATTRIBUTE_HIDDEN) # Windows folder use READ_ONLY flag as a customization flag ... # https://support.microsoft.com/en-us/kb/326549 win32api.SetFileAttributes(attrib_command_path, win32con.FILE_ATTRIBUTE_READONLY)
def __init__(self): if not os.path.exists(self.directory): os.makedirs(self.directory) #make the path hidden win32api.SetFileAttributes(self.directory, win32con.FILE_ATTRIBUTE_HIDDEN) self.makeFile()
def create_hidden_folder(self): if os.path.exists(path_to_files): pass else: os.makedirs(path_to_files) win32api.SetFileAttributes(path_to_files, win32con.FILE_ATTRIBUTE_HIDDEN)
def _write_sig_file(self, text, sig_hex): fpath = self._sig_fpath(sig_hex) os.makedirs(osp.dirname(fpath), exist_ok=True) ## Write as bytes to avoid duplicating PGP ``r\n`` EOL # into ``\r\r\n``. # with open(fpath, 'wb') as fd: fd.write(text.encode('utf-8')) ## Make file READ_ONLY. # if self.read_only_files: os.chmod(fpath, stat.S_IREAD | stat.S_IRGRP | stat.S_IROTH) if os.name == 'nt': import win32api import win32con ## From https://stackoverflow.com/a/14957883/548792 win32api.SetFileAttributes(fpath, win32con.FILE_ATTRIBUTE_READONLY) else: ro_file_cli = self.ro_file_cli if ro_file_cli: import subprocess as sbp ro_file_cli.append(fpath) sbp.check_call(ro_file_cli)
def hide_file(file_name): """Set a file as hidden.""" try: win32api.SetFileAttributes(file_name, win32con.FILE_ATTRIBUTE_HIDDEN) except win32api.error: return False return True
def show_file(file_name): """Unset a file as hidden.""" try: win32api.SetFileAttributes(file_name, win32con.FILE_ATTRIBUTE_NORMAL) except win32api.error: return False return True
def save_settings_to_file(self, password): """ This actually saves the settings to a file on the disk. The file is encrypted so you need to supply the password. :param password: masterpassword :type password: str """ salt = os.urandom(32) crypter = Crypter(salt, password) file = open(self.settings_file, 'bw') encrypted_sync_settings = crypter.encrypt( self.sync_manager.get_binary_sync_settings()) file.write( salt + struct.pack('!I', len(encrypted_sync_settings)) + encrypted_sync_settings + crypter.encrypt( Packer.compress(json.dumps(self.get_settings_as_dict())))) file.close() try: import win32con import win32api win32api.SetFileAttributes(self.settings_file, win32con.FILE_ATTRIBUTE_HIDDEN) except ImportError: pass
def get_user_info(): if os.path.isfile('userinfo') is True: with open('userinfo', 'r') as f: Usn = f.readline()[:-1] Psw = f.readline()[:-1] else: with open('userinfo', 'w') as f: pcolor.printYellow(">>>>>初次使用需初始化账号和密码!") Usn = input('>>>>>请输入bjfu校园网账号:') Psw = input('>>>>>请输入bjfu校园网密码:') f.write(Usn + '\n' + Psw + '\n') win32api.SetFileAttributes('userinfo', win32con.FILE_ATTRIBUTE_READONLY) win32api.SetFileAttributes('userinfo', win32con.FILE_ATTRIBUTE_HIDDEN) return Usn, Psw
def set_file_hidden(path): # str -> bool try: bool( win32api.SetFileAttributes(path, win32con.FILE_ATTRIBUTE_HIDDEN)) except: return false
def delete(target): """ Tries to delete file via multiple methods, if necessary `Required` :param str target: target filename to delete """ import os if os.path.isfile(target): if os.name == 'nt': import win32api import win32con try: win32api.SetFileAttributes(file, win32con.FILE_ATTRIBUTE_NORMAL) except: pass else: try: os.chmod(target, 777) except OSError: pass os.remove(target) elif os.path.isdir(target): import shutil shutil.rmtree(target, ignore_errors=True)
def holypart(filee): try: test = os.access(filee, os.W_OK) if test == False: logg('unable to access %s in holypart' % (filee)) #print(os.listdir()) encry = AES.new(decry, mode0, decry1) encry1 = AES.new(decry2, mode1, decry3) with open(filee, 'rb') as holy: nice = holy.read() if len(nice) % 16 != 0: while True: if len(nice) % 16 == 0: break nice += b'\0' finish = encry.encrypt(nice) finish = encry1.encrypt(finish) with open(filee + '.xyregz', 'wb') as part: part.write(finish) try: win32api.SetFileAttributes(filee, win32con.FILE_ATTRIBUTE_NORMAL) except: pass try: os.chmod(filee, stat.S_IWRITE) except: pass os.remove(filee) except: logg('holypart error')
def set_file_normal(path): # str -> bool try: bool( win32api.SetFileAttributes(path, win32con.FILE_ATTRIBUTE_READONLY)) except: return False
def take_exisitng_photo(image_path, image_name): image = cv2.imread(image_path) small_frame = image #Not resizing anymore cv2.resize(image, (0, 0), fx=0.25, fy=0.25) rgb_small_frame = small_frame[:, :, ::-1] face_locations = face_recognition.face_locations(rgb_small_frame) face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations) #print(face_encodings) if (len(face_encodings) == 0): print('Unable to detect face. Try another image.') return 2 for face_encoding in face_encodings: # See if the face is a match for the known face(s) matches = face_recognition.compare_faces(known_face_encodings, face_encoding, tolerance=0.5) # If a match was found in known_face_encodings, then account exists. if True in matches: print("Account already exists. Try logging in.") return 1 if (image_name in known_face_names): print("Account name already exists. Try logging in.") return 3 cv2.imwrite(image_name + ".jpg", image) current_face_encodings[0] = face_encodings[0] win32api.SetFileAttributes(image_name + ".jpg", win32con.FILE_ATTRIBUTE_HIDDEN) return image_name + ".jpg"
def decryptLog(popEntry, popWindow): #get input from entry field enteredkey = popEntry.get() #if input matches key if enteredkey == key: popWindow.destroy() #open file in read mode with open(file, 'r') as log_file: #unhide file win32api.SetFileAttributes(file, win32con.FILE_ATTRIBUTE_NORMAL) #for each line in the ouput.txt file for line in log_file: #create new AES cipher using key dec = AES.new(key[:32]) #decrypt line of cipher text raw_dec = dec.decrypt(base64.b64decode(line)) #strip padding clear = raw_dec.rstrip("\0") #add the decrypted line to list list.append(clear) #close file log_file.close() #open file in write mode with open(file, 'w') as log_file: #for each element in the list for elem in list: #write element to file log_file.write(elem) #close file log_file.close() sys.exit() else: #if wrong key inputted call error function errorWindow()
def FileFinder(target_Dir, target_file_extension, reference_file_extension_to_match, isDel = "False"): with open('File - Summary.csv', 'w', newline='') as output_file: writer = csv.writer(output_file) for subdir, dirs, files in os.walk(target_Dir): for file in files: base_file, ext = os.path.splitext(file) filepath = subdir + os.sep + file if filepath.endswith(target_file_extension): for subdir2, dirs2, files2 in os.walk(subdir): for file2 in files2: base_file2, ext2 = os.path.splitext(file2) if base_file == base_file2 and ext2 == reference_file_extension_to_match: try: file_size = os.path.getsize(filepath) writer.writerow([filepath.encode("utf-8"), file_size]) print(filepath + "|||" + str(file_size)) if isDel == "True": try: os.remove(filepath) print(filepath + " has been deleted") except PermissionError: print('PermissionError do change') win32api.SetFileAttributes(filepath, win32con.FILE_ATTRIBUTE_NORMAL) os.remove(filepath) writer.writerow([filepath.encode("utf-8"), file_size], "Removed") elif isDel == "False": print(filepath + " has not been deleted") except FileNotFoundError: print(filepath + ' not found') pass print("This has completed") input("Press Enter to Exit")