Python ntpath.dirname() Examples
The following are 30
code examples of ntpath.dirname().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
ntpath
, or try the search function
.
Example #1
Source File: _os.py From smbprotocol with MIT License | 6 votes |
def removedirs(name, **kwargs): """ Remove directories recursively. Works like rmdir() except that, if the leaf directory is successfully removed, removedirs() tries to successively remove every parent directory mentioned in path until an error is raised (which is ignored, because it generally means that a parent directory is not empty). :param name: The directory to start removing recursively from. :param kwargs: Common SMB Session arguments for smbclient. """ remove_dir = ntpath.normpath(name) while True: try: rmdir(remove_dir, **kwargs) except (SMBResponseException, OSError): return else: remove_dir = ntpath.dirname(remove_dir)
Example #2
Source File: winregistry.py From PiBunny with MIT License | 6 votes |
def getValue(self, keyValue): # returns a tuple with (ValueType, ValueData) for the requested keyValue regKey = ntpath.dirname(keyValue) regValue = ntpath.basename(keyValue) key = self.findKey(regKey) if key is None: return None if key['NumValues'] > 0: valueList = self.__getValueBlocks(key['OffsetValueList'], key['NumValues']+1) for value in valueList: if value['Name'] == regValue: return value['ValueType'], self.__getValueData(value) elif regValue == 'default' and value['Flag'] <=0: return value['ValueType'], self.__getValueData(value) return None
Example #3
Source File: winregistry.py From Slackor with GNU General Public License v3.0 | 6 votes |
def getValue(self, keyValue): # returns a tuple with (ValueType, ValueData) for the requested keyValue regKey = ntpath.dirname(keyValue) regValue = ntpath.basename(keyValue) key = self.findKey(regKey) if key is None: return None if key['NumValues'] > 0: valueList = self.__getValueBlocks(key['OffsetValueList'], key['NumValues']+1) for value in valueList: if value['Name'] == b(regValue): return value['ValueType'], self.__getValueData(value) elif regValue == 'default' and value['Flag'] <=0: return value['ValueType'], self.__getValueData(value) return None
Example #4
Source File: malprocfind.py From volatility_plugins with GNU General Public License v2.0 | 6 votes |
def check_proc_susp_path(self, process): if int(process.UniqueProcessId) == 4: return True if process.Peb == None or \ process.Peb.ProcessParameters == None or \ process.Peb.ProcessParameters.ImagePathName == None: return None suspicious = False for r in list_bad_paths: if r.match(ntpath.dirname(str(process.Peb.ProcessParameters.ImagePathName).lower())): suspicious = True return not suspicious # Checks the process parent
Example #5
Source File: tvshows.py From jellyfin-kodi with GNU General Public License v3.0 | 6 votes |
def get_path_filename(self, obj): ''' Get the path and build it into protocol://path ''' if self.direct_path: if '\\' in obj['Path']: obj['Path'] = "%s\\" % obj['Path'] obj['TopLevel'] = "%s\\" % dirname(dirname(obj['Path'])) else: obj['Path'] = "%s/" % obj['Path'] obj['TopLevel'] = "plugin://plugin.video.jellyfin/" if not validate(obj['Path']): raise Exception("Failed to validate path. User stopped.") else: obj['TopLevel'] = "plugin://plugin.video.jellyfin/%s/" % obj['LibraryId'] obj['Path'] = "%s%s/" % (obj['TopLevel'], obj['Id'])
Example #6
Source File: __init__.py From aenet with BSD 3-Clause "New" or "Revised" License | 6 votes |
def extract_fbank_htk(self, scriptfile): ''' :param scriptfile: path to the HCopy's script file :return: list of path to feature files ''' with open(scriptfile, 'r') as scpf: featfiles = scpf.readlines() featfiles = [f.split(' ')[1].replace('\n', '') for f in featfiles] for f in featfiles: if not os.path.exists(ntpath.dirname(f)): os.makedirs(ntpath.dirname(f)) cmd = self.HCopyExe + ' -C ' + self.HConfigFile + ' -S ' + scriptfile os.system(cmd) return featfiles
Example #7
Source File: winregistry.py From cracke-dit with MIT License | 6 votes |
def getValue(self, keyValue): # returns a tuple with (ValueType, ValueData) for the requested keyValue regKey = ntpath.dirname(keyValue) regValue = ntpath.basename(keyValue) key = self.findKey(regKey) if key is None: return None if key['NumValues'] > 0: valueList = self.__getValueBlocks(key['OffsetValueList'], key['NumValues']+1) for value in valueList: if value['Name'] == regValue: return value['ValueType'], self.__getValueData(value) elif regValue == 'default' and value['Flag'] <=0: return value['ValueType'], self.__getValueData(value) return None
Example #8
Source File: appSearch.py From appcompatprocessor with Apache License 2.0 | 6 votes |
def runIndexedSearch(dbfilenameFullPath, search_space, options): # todo: Handle duplicate hit supression logger.info("Performing indexed search") DB = appDB.DBClass(dbfilenameFullPath, True, settings.__version__) DB.appInitDB() DB.appConnectDB() searchTerm = options.searchLiteral[0] numHits = 0 # Run actual indexed query data = DB.Query("SELECT RowID FROM Entries_FilePaths WHERE %s == '%s';" % (search_space, searchTerm)) if data: # results = [] # results.append(('cyan', "FileName,HitCount".split(','))) with open(options.outputFile, "w") as text_file: with open(os.path.join(ntpath.dirname(options.outputFile), ntpath.splitext(options.outputFile)[0] + ".mmd"), "w") as markdown_file: for row in data: # results.append(('white', row)) record = retrieveSearchData(row[0], DB, search_space) saveSearchData(record, None, None, text_file, markdown_file) numHits += 1 # outputcolum(results) return (numHits, 0, []) else: return(0, 0, [])
Example #9
Source File: winregistry.py From CVE-2017-7494 with GNU General Public License v3.0 | 6 votes |
def getValue(self, keyValue): # returns a tuple with (ValueType, ValueData) for the requested keyValue regKey = ntpath.dirname(keyValue) regValue = ntpath.basename(keyValue) key = self.findKey(regKey) if key is None: return None if key['NumValues'] > 0: valueList = self.__getValueBlocks(key['OffsetValueList'], key['NumValues']+1) for value in valueList: if value['Name'] == regValue: return value['ValueType'], self.__getValueData(value) elif regValue == 'default' and value['Flag'] <=0: return value['ValueType'], self.__getValueData(value) return None
Example #10
Source File: DialogUtils.py From kicad_mmccoo with Apache License 2.0 | 5 votes |
def OnButton(self, event): fileDialog = wx.FileDialog(self, "open xyz", defaultDir=ntpath.dirname(self.value), defaultFile=ntpath.basename(self.value), style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) if (self.wildcard != None): fileDialog.SetWildcard(self.wildcard) if fileDialog.ShowModal() == wx.ID_CANCEL: return self.value = fileDialog.GetPath() self.selectedfile.SetValue(self.value)
Example #11
Source File: workspace.py From autosar with MIT License | 5 votes |
def _adjustFileRef(self,fileRef,basedir): basename = ntpath.basename(fileRef['path']) dirname=ntpath.normpath(ntpath.join(basedir,ntpath.dirname(fileRef['path']))) retval=ntpath.join(dirname,basename) if os.path.sep == '/': #are we running in cygwin/Linux? retval = retval.replace(r'\\','/') return retval
Example #12
Source File: dcf.py From autosar with MIT License | 5 votes |
def _adjust_elem(self, elem, basedir): basename = ntpath.basename(elem['path']) dirname = ntpath.normpath(ntpath.join(basedir,ntpath.dirname(elem['path']))) elem['path']=ntpath.join(dirname,basename) if os.path.sep == '/': #are we running in cygwin/Linux? elem['path'] = elem['path'].replace(r'\\','/')
Example #13
Source File: dcf.py From autosar with MIT License | 5 votes |
def parse(self, filename): """ Parses file references and external file references from a DCF file """ basedir = ntpath.dirname(filename) xml_root = self._open_xml(filename) dcf = self._process_xml(xml_root) dcf.adjust_file_refs(basedir) return dcf
Example #14
Source File: registry-read.py From Slackor with GNU General Public License v3.0 | 5 votes |
def getClass(reg, className): regKey = ntpath.dirname(className) regClass = ntpath.basename(className) value = reg.getClass(className) if value is None: return print("[%s]" % regKey) print("Value for Class %s: \n" % regClass, end=' ') winregistry.hexdump(value,' ')
Example #15
Source File: registry-read.py From Slackor with GNU General Public License v3.0 | 5 votes |
def getValue(reg, keyValue): regKey = ntpath.dirname(keyValue) regValue = ntpath.basename(keyValue) value = reg.getValue(keyValue) print("[%s]\n" % regKey) if value is None: return print("Value for %s:\n " % regValue, end=' ') reg.printValue(value[0],value[1])
Example #16
Source File: _os.py From smbprotocol with MIT License | 5 votes |
def renames(old, new, **kwargs): """ Recursive directory or file renaming function. Works like rename(), except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned away using removedirs(). :param old: The path to the file or directory to rename. :param new: The path to rename the file or directory to. :param kwargs: Common SMB Session arguments for smbclient. """ makedirs(ntpath.dirname(new), exist_ok=True, **kwargs) rename(old, new, **kwargs) removedirs(ntpath.dirname(old), **kwargs)
Example #17
Source File: ProjectManager.py From legion with GNU General Public License v3.0 | 5 votes |
def openExistingProject(self, projectName: str, projectType: str = "legion") -> Project: self.logger.info(f"Opening existing project: {projectName}...") database = self.__createDatabase(projectName) workingDirectory = f"{ntpath.dirname(projectName)}/" outputFolder, _ = self.__determineOutputFolder(projectName, projectType) runningFolder = self.shell.create_temporary_directory(suffix="-running", prefix=projectType + '-', directory="./tmp/") (usernameWordList, passwordWordList) = self.__createUsernameAndPasswordWordLists(outputFolder) projectProperties = ProjectProperties( projectName=projectName, workingDirectory=workingDirectory, projectType=projectType, isTemporary=False, outputFolder=outputFolder, runningFolder=runningFolder, usernamesWordList=usernameWordList, passwordWordList=passwordWordList, storeWordListsOnExit=True ) repositoryContainer = self.repositoryFactory.buildRepositories(database) return Project(projectProperties, repositoryContainer, database)
Example #18
Source File: common.py From POC-EXP with GNU General Public License v3.0 | 5 votes |
def directoryPath(filepath): """ Returns directory path for a given filepath >>> directoryPath('/var/log/apache.log') '/var/log' """ retVal = filepath if filepath: retVal = ntpath.dirname(filepath) if isWindowsDriveLetterPath(filepath) else posixpath.dirname(filepath) return retVal
Example #19
Source File: misc.py From POC-EXP with GNU General Public License v3.0 | 5 votes |
def getRemoteTempPath(self): if not conf.tmpPath and Backend.isDbms(DBMS.MSSQL): debugMsg = "identifying Microsoft SQL Server error log directory " debugMsg += "that sqlmap will use to store temporary files with " debugMsg += "commands' output" logger.debug(debugMsg) _ = unArrayizeValue(inject.getValue("SELECT SERVERPROPERTY('ErrorLogFileName')", safeCharEncode=False)) if _: conf.tmpPath = ntpath.dirname(_) if not conf.tmpPath: if Backend.isOs(OS.WINDOWS): if conf.direct: conf.tmpPath = "%TEMP%" else: self.checkDbmsOs(detailed=True) if Backend.getOsVersion() in ("2000", "NT"): conf.tmpPath = "C:/WINNT/Temp" elif Backend.isOs("XP"): conf.tmpPath = "C:/Documents and Settings/All Users/Application Data/Temp" else: conf.tmpPath = "C:/Windows/Temp" else: conf.tmpPath = "/tmp" if re.search(r"\A[\w]:[\/\\]+", conf.tmpPath, re.I): Backend.setOs(OS.WINDOWS) conf.tmpPath = normalizePath(conf.tmpPath) conf.tmpPath = ntToPosixSlashes(conf.tmpPath) singleTimeDebugMessage("going to use %s as temporary files directory" % conf.tmpPath) hashDBWrite(HASHDB_KEYS.CONF_TMP_PATH, conf.tmpPath) return conf.tmpPath
Example #20
Source File: functions.py From eqllib with MIT License | 5 votes |
def run(cls, path): if path is not None: return ntpath.dirname(path)
Example #21
Source File: os.py From odoo13-x64 with GNU General Public License v3.0 | 5 votes |
def _execvpe(file, args, env=None): if env is not None: exec_func = execve argrest = (args, env) else: exec_func = execv argrest = (args,) env = environ if path.dirname(file): exec_func(file, *argrest) return saved_exc = None path_list = get_exec_path(env) if name != 'nt': file = fsencode(file) path_list = map(fsencode, path_list) for dir in path_list: fullname = path.join(dir, file) try: exec_func(fullname, *argrest) except (FileNotFoundError, NotADirectoryError) as e: last_exc = e except OSError as e: last_exc = e if saved_exc is None: saved_exc = e if saved_exc is not None: raise saved_exc raise last_exc
Example #22
Source File: common.py From EasY_HaCk with Apache License 2.0 | 5 votes |
def directoryPath(filepath): """ Returns directory path for a given filepath >>> directoryPath('/var/log/apache.log') '/var/log' """ retVal = filepath if filepath: retVal = ntpath.dirname(filepath) if isWindowsDriveLetterPath(filepath) else posixpath.dirname(filepath) return retVal
Example #23
Source File: misc.py From EasY_HaCk with Apache License 2.0 | 5 votes |
def getRemoteTempPath(self): if not conf.tmpPath and Backend.isDbms(DBMS.MSSQL): debugMsg = "identifying Microsoft SQL Server error log directory " debugMsg += "that sqlmap will use to store temporary files with " debugMsg += "commands' output" logger.debug(debugMsg) _ = unArrayizeValue(inject.getValue("SELECT SERVERPROPERTY('ErrorLogFileName')", safeCharEncode=False)) if _: conf.tmpPath = ntpath.dirname(_) if not conf.tmpPath: if Backend.isOs(OS.WINDOWS): if conf.direct: conf.tmpPath = "%TEMP%" else: self.checkDbmsOs(detailed=True) if Backend.getOsVersion() in ("2000", "NT"): conf.tmpPath = "C:/WINNT/Temp" elif Backend.isOs("XP"): conf.tmpPath = "C:/Documents and Settings/All Users/Application Data/Temp" else: conf.tmpPath = "C:/Windows/Temp" else: conf.tmpPath = "/tmp" if re.search(r"\A[\w]:[\/\\]+", conf.tmpPath, re.I): Backend.setOs(OS.WINDOWS) conf.tmpPath = normalizePath(conf.tmpPath) conf.tmpPath = ntToPosixSlashes(conf.tmpPath) singleTimeDebugMessage("going to use '%s' as temporary files directory" % conf.tmpPath) hashDBWrite(HASHDB_KEYS.CONF_TMP_PATH, conf.tmpPath) return conf.tmpPath
Example #24
Source File: os.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _execvpe(file, args, env=None): if env is not None: exec_func = execve argrest = (args, env) else: exec_func = execv argrest = (args,) env = environ if path.dirname(file): exec_func(file, *argrest) return saved_exc = None path_list = get_exec_path(env) if name != 'nt': file = fsencode(file) path_list = map(fsencode, path_list) for dir in path_list: fullname = path.join(dir, file) try: exec_func(fullname, *argrest) # iOS: we return from execs. That surprises python return except (FileNotFoundError, NotADirectoryError) as e: last_exc = e except OSError as e: last_exc = e if saved_exc is None: saved_exc = e if saved_exc is not None: raise saved_exc raise last_exc
Example #25
Source File: registry-read.py From PiBunny with MIT License | 5 votes |
def getClass(reg, className): regKey = ntpath.dirname(className) regClass = ntpath.basename(className) value = reg.getClass(className) if value is None: return print "[%s]" % regKey print "Value for Class %s: \n" % regClass, winregistry.hexdump(value,' ')
Example #26
Source File: registry-read.py From PiBunny with MIT License | 5 votes |
def getValue(reg, keyValue): regKey = ntpath.dirname(keyValue) regValue = ntpath.basename(keyValue) value = reg.getValue(keyValue) print "[%s]\n" % regKey if value is None: return print "Value for %s:\n " % regValue, reg.printValue(value[0],value[1])
Example #27
Source File: smb3.py From PiBunny with MIT License | 5 votes |
def listPath(self, shareName, path, password = None): # ToDo: Handle situations where share is password protected path = string.replace(path,'/', '\\') path = ntpath.normpath(path) if len(path) > 0 and path[0] == '\\': path = path[1:] treeId = self.connectTree(shareName) fileId = None try: # ToDo, we're assuming it's a directory, we should check what the file type is fileId = self.create(treeId, ntpath.dirname(path), FILE_READ_ATTRIBUTES | FILE_READ_DATA ,FILE_SHARE_READ | FILE_SHARE_WRITE |FILE_SHARE_DELETE, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, FILE_OPEN, 0) res = '' files = [] from impacket import smb while True: try: res = self.queryDirectory( treeId, fileId, ntpath.basename(path), maxBufferSize = 65535, informationClass = FILE_FULL_DIRECTORY_INFORMATION ) nextOffset = 1 while nextOffset != 0: fileInfo = smb.SMBFindFileFullDirectoryInfo(smb.SMB.FLAGS2_UNICODE) fileInfo.fromString(res) files.append(smb.SharedFile(fileInfo['CreationTime'],fileInfo['LastAccessTime'],fileInfo['LastChangeTime'],fileInfo['EndOfFile'],fileInfo['AllocationSize'],fileInfo['ExtFileAttributes'],fileInfo['FileName'].decode('utf-16le'), fileInfo['FileName'].decode('utf-16le'))) nextOffset = fileInfo['NextEntryOffset'] res = res[nextOffset:] except SessionError, e: if (e.get_error_code()) != STATUS_NO_MORE_FILES: raise break finally: if fileId is not None: self.close(treeId, fileId) self.disconnectTree(treeId) return files
Example #28
Source File: _os.py From smbprotocol with MIT License | 5 votes |
def makedirs(path, exist_ok=False, **kwargs): """ Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. If exist_ok is False (the default), an OSError is raised if the target directory already exists. :param path: The path to the directory to create. :param exist_ok: Set to True to not fail if the target directory already exists. :param kwargs: Common SMB Session arguments for smbclient. """ create_queue = [ntpath.normpath(path)] present_parent = None while create_queue: mkdir_path = create_queue[-1] try: mkdir(mkdir_path, **kwargs) except OSError as err: if err.errno == errno.EEXIST: present_parent = mkdir_path create_queue.pop(-1) if not create_queue and not exist_ok: raise elif err.errno == errno.ENOENT: # Check if the parent path has already been created to avoid getting in an endless loop. parent_path = ntpath.dirname(mkdir_path) if present_parent == parent_path: raise else: create_queue.append(parent_path) else: raise else: create_queue.pop(-1)
Example #29
Source File: os.py From android_universal with MIT License | 5 votes |
def _execvpe(file, args, env=None): if env is not None: exec_func = execve argrest = (args, env) else: exec_func = execv argrest = (args,) env = environ if path.dirname(file): exec_func(file, *argrest) return saved_exc = None path_list = get_exec_path(env) if name != 'nt': file = fsencode(file) path_list = map(fsencode, path_list) for dir in path_list: fullname = path.join(dir, file) try: exec_func(fullname, *argrest) except (FileNotFoundError, NotADirectoryError) as e: last_exc = e except OSError as e: last_exc = e if saved_exc is None: saved_exc = e if saved_exc is not None: raise saved_exc raise last_exc
Example #30
Source File: misc.py From NoobSec-Toolkit with GNU General Public License v2.0 | 5 votes |
def getRemoteTempPath(self): if not conf.tmpPath and Backend.isDbms(DBMS.MSSQL): debugMsg = "identifying Microsoft SQL Server error log directory " debugMsg += "that sqlmap will use to store temporary files with " debugMsg += "commands' output" logger.debug(debugMsg) _ = unArrayizeValue(inject.getValue("SELECT SERVERPROPERTY('ErrorLogFileName')", safeCharEncode=False)) if _: conf.tmpPath = ntpath.dirname(_) if not conf.tmpPath: if Backend.isOs(OS.WINDOWS): if conf.direct: conf.tmpPath = "%TEMP%" else: self.checkDbmsOs(detailed=True) if Backend.getOsVersion() in ("2000", "NT"): conf.tmpPath = "C:/WINNT/Temp" elif Backend.isOs("XP"): conf.tmpPath = "C:/Documents and Settings/All Users/Application Data/Temp" else: conf.tmpPath = "C:/Windows/Temp" else: conf.tmpPath = "/tmp" if re.search(r"\A[\w]:[\/\\]+", conf.tmpPath, re.I): Backend.setOs(OS.WINDOWS) conf.tmpPath = normalizePath(conf.tmpPath) conf.tmpPath = ntToPosixSlashes(conf.tmpPath) singleTimeDebugMessage("going to use %s as temporary files directory" % conf.tmpPath) hashDBWrite(HASHDB_KEYS.CONF_TMP_PATH, conf.tmpPath) return conf.tmpPath