Python源码示例:ntpath.dirname()
示例1
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)
示例2
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
示例3
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, [])
示例4
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
示例5
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
示例6
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'])
示例7
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
示例8
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
示例9
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
示例10
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)
示例11
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)
示例12
def run(cls, path):
if path is not None:
return ntpath.dirname(path)
示例13
def gen_wrap_str(self):
dir_path = ntpath.dirname(self.file) + '/'
wrap_str = '''
sess = None
def tf_score({4}):
"Output: {5}"
import tensorflow as tf
import numpy as np
global sess
global score_op
global input_op
#If it is called for the first time, restore the model and necessary operations
if sess is None:
sess=tf.Session()
#load meta graph and restore weights
saver = tf.train.import_meta_graph('{0}')
saver.restore(sess,tf.train.latest_checkpoint('{1}'))
graph = tf.get_default_graph()
#restore the ops. Both ops were pre-defined in the model.
input_op = graph.get_tensor_by_name("{2}:0") #op to feed input data
score_op = graph.get_tensor_by_name("{3}:0") #op to score the input
#Note that the feed value of x has shape (?,xyz), NOT (,xyz)
{4}_wrap = np.array([{4}])
{5} = sess.run(score_op, feed_dict={{input_op: {4}_wrap}})[0]
if isinstance({5}, np.ndarray):
{5} = {5}.tolist()
else:
{5} = {5}.item()
return {5}'''.format(self.file, dir_path, self.input_op, self.score_op,
self.input_name, self.output_name)
return wrap_str
示例14
def init(self, config=None, server='https://pipe.databolt.tech', reset=False):
"""
Initialize config with content
Args:
config (dict): manually pass config object
server (str): location of REST API server
reset (bool): force reset of an existing config
"""
if os.path.exists(self.filecfg) and not reset and self.profile in self._loadall():
# todo: why does Path(self.filecfg).exists() not work in pytest?
warnings.warn('Config for profile {} in {} already exists, skipping init. Use reset=True to reset config.'.format(self.profile,self.filecfg))
return None
if not config:
config = {}
if 'server' not in config:
config['server'] = server
if 'filerepo' not in config:
config['filerepo'] = '~/d6tpipe'
p = Path(config['filerepo'])
p2 = p/'files/{}/'.format(self.profile)
config['filereporoot'] = str(p)
config['filerepo'] = str(p2)
if 'filedb' not in config:
config['filedb'] = str(p2/'.filedb.json')
# create config file if doesn't exist
if not os.path.exists(self.filecfg):
if not os.path.exists(ntpath.dirname(self.filecfg)):
os.makedirs(ntpath.dirname(self.filecfg))
self._save(config)
示例15
def open_value(self, path):
key = self.open_key(ntpath.dirname(path))
return key.open_value(ntpath.basename(path))
示例16
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
示例17
def _create_remote_dir(state, host, remote_filename, user, group):
# Always use POSIX style path as local might be Windows, remote always *nix
remote_dirname = ntpath.dirname(remote_filename)
if remote_dirname:
yield directory(
state, host, remote_dirname,
user=user, group=group,
)
示例18
def processFile(self, file_fullpath, hostID, instanceID, rowsData):
rowNumber = 0
file_object = loadFile(file_fullpath)
rows = _processAmCacheFile_StringIO(file_object)
file_object.close()
for r in rows:
namedrow = settings.EntriesFields(HostID = hostID, EntryType = settings.__AMCACHE__,
RowNumber = rowNumber,
FilePath = (None if r.path == None else ntpath.dirname(r.path)),
FileName = (None if r.path == None else ntpath.basename(r.path)),
Size = r.size,
ExecFlag = 'True',
SHA1 = (None if r.sha1 == None else r.sha1[4:]),
FileDescription = r.file_description,
FirstRun = r.first_run,
Created = r.created_timestamp,
Modified1 = r.modified_timestamp,
Modified2 = r.modified_timestamp2,
LinkerTS = r.linker_timestamp,
Product = r.product,
Company = r.company,
PE_sizeofimage = r.pe_sizeofimage,
Version_number = r.version_number,
Version = r.version,
Language = r.language,
Header_hash = r.header_hash,
PE_checksum = r.pe_checksum,
SwitchBackContext = r.switchbackcontext,
InstanceID = instanceID)
rowsData.append(namedrow)
rowNumber += 1
示例19
def processFile(self, file_fullpath, hostID, instanceID, rowsData):
rowNumber = 0
file_object = loadFile(file_fullpath)
rows = _processAmCacheFile_StringIO(file_object)
file_object.close()
for r in rows:
namedrow = settings.EntriesFields(HostID = hostID, EntryType = settings.__AMCACHE__,
RowNumber = rowNumber,
FilePath = (None if r.path == None else ntpath.dirname(r.path)),
FileName = (None if r.path == None else ntpath.basename(r.path)),
Size = r.size, ExecFlag = 'True',
SHA1 = (None if r.sha1 == None else r.sha1[4:]),
FileDescription = r.file_description,
FirstRun = r.first_run,
Created = r.created_timestamp,
Modified1 = r.modified_timestamp,
Modified2 = r.modified_timestamp2,
LinkerTS = r.linker_timestamp,
Product = r.product,
Company = r.company,
PE_sizeofimage = r.pe_sizeofimage,
Version_number = r.version_number,
Version = r.version,
Language = r.language,
Header_hash = r.header_hash,
PE_checksum = r.pe_checksum,
SwitchBackContext = r.switchbackcontext,
InstanceID = instanceID)
rowsData.append(namedrow)
rowNumber += 1
示例20
def KnownBadRegexCount(file_full_path):
file_path = ntpath.dirname(file_full_path)
file_name, file_extension = os.path.splitext(file_full_path)
# Load base file
total_regex_count = KnownBadRegexCountFile(file_full_path)
# Load extra files
for filename in glob.iglob(file_name + '-*' + file_extension):
total_regex_count += KnownBadRegexCountFile(filename)
return total_regex_count
示例21
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
示例22
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
示例23
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
示例24
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
示例25
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
示例26
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
示例27
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
示例28
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
示例29
def get_value(self, value_path, throw = True):
if self.root is None:
self.setup()
key_path = ntpath.dirname(value_path)
value_name = ntpath.basename(value_path)
if value_name == 'default':
value_name = ''
key = self.find_key(key_path, throw)
if key is None:
return None
res = winreg.QueryValueEx(key, value_name)
return (res[1], res[0])
示例30
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