def do_cat(self, line, command = sys.stdout.write):
pathName = string.replace(line,'/','\\')
pathName = ntpath.normpath(ntpath.join(self.pwd,pathName))
res = self.findPathName(pathName)
if res is None:
logging.error("Not found!")
return
if res.isDirectory() > 0:
logging.error("It's a directory!")
return
if res.isCompressed() or res.isEncrypted() or res.isSparse():
logging.error('Cannot handle compressed/encrypted/sparse files! :(')
return
stream = res.getStream(None)
chunks = 4096*10
written = 0
for i in range(stream.getDataSize()/chunks):
buf = stream.read(i*chunks, chunks)
written += len(buf)
command(buf)
if stream.getDataSize() % chunks:
buf = stream.read(written, stream.getDataSize() % chunks)
command(buf)
logging.info("%d bytes read" % stream.getDataSize())
python类normpath()的实例源码
def mkdir(self, shareName, pathName, password = None):
# ToDo: Handle situations where share is password protected
pathName = string.replace(pathName,'/', '\\')
pathName = ntpath.normpath(pathName)
if len(pathName) > 0 and pathName[0] == '\\':
pathName = pathName[1:]
treeId = self.connectTree(shareName)
fileId = None
try:
fileId = self.create(treeId, pathName,GENERIC_ALL ,FILE_SHARE_READ | FILE_SHARE_WRITE |FILE_SHARE_DELETE, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, FILE_CREATE, 0)
finally:
if fileId is not None:
self.close(treeId, fileId)
self.disconnectTree(treeId)
return True
def rmdir(self, shareName, pathName, password = None):
# ToDo: Handle situations where share is password protected
pathName = string.replace(pathName,'/', '\\')
pathName = ntpath.normpath(pathName)
if len(pathName) > 0 and pathName[0] == '\\':
pathName = pathName[1:]
treeId = self.connectTree(shareName)
fileId = None
try:
fileId = self.create(treeId, pathName, desiredAccess=DELETE | FILE_READ_ATTRIBUTES | SYNCHRONIZE,
shareMode=FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
creationOptions=FILE_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT,
creationDisposition=FILE_OPEN, fileAttributes=0)
from impacket import smb
delete_req = smb.SMBSetFileDispositionInfo()
delete_req['DeletePending'] = True
self.setInfo(treeId, fileId, inputBlob=delete_req, fileInfoClass=SMB2_FILE_DISPOSITION_INFO)
finally:
if fileId is not None:
self.close(treeId, fileId)
self.disconnectTree(treeId)
return True
def storeFile(self, shareName, path, callback, mode = FILE_OVERWRITE_IF, offset = 0, password = None, shareAccessMode = FILE_SHARE_WRITE):
# 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:
fileId = self.create(treeId, path, FILE_WRITE_DATA, shareAccessMode, FILE_NON_DIRECTORY_FILE, mode, 0)
finished = False
writeOffset = offset
while not finished:
data = callback(self._Connection['MaxWriteSize'])
if len(data) == 0:
break
written = self.write(treeId, fileId, data, writeOffset, len(data))
writeOffset += written
finally:
if fileId is not None:
self.close(treeId, fileId)
self.disconnectTree(treeId)
def checkIntegrity():
"""
Checks integrity of code files during the unhandled exceptions
"""
if not paths:
return
logger.debug("running code integrity check")
retVal = True
for checksum, _ in (re.split(r'\s+', _) for _ in getFileItems(paths.CHECKSUM_MD5)):
path = os.path.normpath(os.path.join(paths.SQLMAP_ROOT_PATH, _))
if not os.path.isfile(path):
logger.error("missing file detected '%s'" % path)
retVal = False
elif md5File(path) != checksum:
logger.error("wrong checksum of file '%s' detected" % path)
retVal = False
return retVal
def mkdir(self, shareName, pathName, password = None):
# ToDo: Handle situations where share is password protected
pathName = string.replace(pathName,'/', '\\')
pathName = ntpath.normpath(pathName)
if len(pathName) > 0 and pathName[0] == '\\':
pathName = pathName[1:]
treeId = self.connectTree(shareName)
fileId = None
try:
fileId = self.create(treeId, pathName,GENERIC_ALL ,FILE_SHARE_READ | FILE_SHARE_WRITE |FILE_SHARE_DELETE, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, FILE_CREATE, 0)
finally:
if fileId is not None:
self.close(treeId, fileId)
self.disconnectTree(treeId)
return True
def rmdir(self, shareName, pathName, password = None):
# ToDo: Handle situations where share is password protected
pathName = string.replace(pathName,'/', '\\')
pathName = ntpath.normpath(pathName)
if len(pathName) > 0 and pathName[0] == '\\':
pathName = pathName[1:]
treeId = self.connectTree(shareName)
fileId = None
try:
fileId = self.create(treeId, pathName, desiredAccess=DELETE | FILE_READ_ATTRIBUTES | SYNCHRONIZE,
shareMode=FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
creationOptions=FILE_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT,
creationDisposition=FILE_OPEN, fileAttributes=0)
from impacket import smb
delete_req = smb.SMBSetFileDispositionInfo()
delete_req['DeletePending'] = True
self.setInfo(treeId, fileId, inputBlob=delete_req, fileInfoClass=SMB2_FILE_DISPOSITION_INFO)
finally:
if fileId is not None:
self.close(treeId, fileId)
self.disconnectTree(treeId)
return True
def remove(self, shareName, pathName, password = None):
# ToDo: Handle situations where share is password protected
pathName = string.replace(pathName,'/', '\\')
pathName = ntpath.normpath(pathName)
if len(pathName) > 0 and pathName[0] == '\\':
pathName = pathName[1:]
treeId = self.connectTree(shareName)
fileId = None
try:
fileId = self.create(treeId, pathName,DELETE | FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_NON_DIRECTORY_FILE | FILE_DELETE_ON_CLOSE, FILE_OPEN, 0)
finally:
if fileId is not None:
self.close(treeId, fileId)
self.disconnectTree(treeId)
return True
def storeFile(self, shareName, path, callback, mode = FILE_OVERWRITE_IF, offset = 0, password = None, shareAccessMode = FILE_SHARE_WRITE):
# 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:
fileId = self.create(treeId, path, FILE_WRITE_DATA, shareAccessMode, FILE_NON_DIRECTORY_FILE, mode, 0)
finished = False
writeOffset = offset
while not finished:
data = callback(self._Connection['MaxWriteSize'])
if len(data) == 0:
break
written = self.write(treeId, fileId, data, writeOffset, len(data))
writeOffset += written
finally:
if fileId is not None:
self.close(treeId, fileId)
self.disconnectTree(treeId)
def printSources(self, hierarchy, commonprefix):
sorteditems = sorted(hierarchy.items(), key=lambda a: a[0].lower())
# First folders, then files
for key, value in sorteditems:
if SCons.Util.is_Dict(value):
self.file.write('\t\t\t<Filter\n'
'\t\t\t\tName="%s"\n'
'\t\t\t\tFilter="">\n' % (key))
self.printSources(value, commonprefix)
self.file.write('\t\t\t</Filter>\n')
for key, value in sorteditems:
if SCons.Util.is_String(value):
file = value
if commonprefix:
file = os.path.join(commonprefix, value)
file = os.path.normpath(file)
self.file.write('\t\t\t<File\n'
'\t\t\t\tRelativePath="%s">\n'
'\t\t\t</File>\n' % (file))
def printSources(self, hierarchy, kind, commonprefix, filter_name):
keywords = {'Source Files': 'ClCompile',
'Header Files': 'ClInclude',
'Local Headers': 'ClInclude',
'Resource Files': 'None',
'Other Files': 'None'}
sorteditems = sorted(hierarchy.items(), key = lambda a: a[0].lower())
# First folders, then files
for key, value in sorteditems:
if SCons.Util.is_Dict(value):
self.printSources(value, kind, commonprefix, filter_name + '\\' + key)
for key, value in sorteditems:
if SCons.Util.is_String(value):
file = value
if commonprefix:
file = os.path.join(commonprefix, value)
file = os.path.normpath(file)
self.file.write('\t\t<%s Include="%s" />\n' % (keywords[kind], file))
self.filters_file.write('\t\t<%s Include="%s">\n'
'\t\t\t<Filter>%s</Filter>\n'
'\t\t</%s>\n' % (keywords[kind], file, filter_name, keywords[kind]))
def mkdir(self, shareName, pathName, password = None):
# ToDo: Handle situations where share is password protected
pathName = string.replace(pathName,'/', '\\')
pathName = ntpath.normpath(pathName)
if len(pathName) > 0 and pathName[0] == '\\':
pathName = pathName[1:]
treeId = self.connectTree(shareName)
fileId = None
try:
fileId = self.create(treeId, pathName,GENERIC_ALL ,FILE_SHARE_READ | FILE_SHARE_WRITE |FILE_SHARE_DELETE, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, FILE_CREATE, 0)
finally:
if fileId is not None:
self.close(treeId, fileId)
self.disconnectTree(treeId)
return True
def rmdir(self, shareName, pathName, password = None):
# ToDo: Handle situations where share is password protected
pathName = string.replace(pathName,'/', '\\')
pathName = ntpath.normpath(pathName)
if len(pathName) > 0 and pathName[0] == '\\':
pathName = pathName[1:]
treeId = self.connectTree(shareName)
fileId = None
try:
fileId = self.create(treeId, pathName, DELETE, FILE_SHARE_DELETE, FILE_DIRECTORY_FILE | FILE_DELETE_ON_CLOSE, FILE_OPEN, 0)
finally:
if fileId is not None:
self.close(treeId, fileId)
self.disconnectTree(treeId)
return True
def remove(self, shareName, pathName, password = None):
# ToDo: Handle situations where share is password protected
pathName = string.replace(pathName,'/', '\\')
pathName = ntpath.normpath(pathName)
if len(pathName) > 0 and pathName[0] == '\\':
pathName = pathName[1:]
treeId = self.connectTree(shareName)
fileId = None
try:
fileId = self.create(treeId, pathName,DELETE | FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_NON_DIRECTORY_FILE | FILE_DELETE_ON_CLOSE, FILE_OPEN, 0)
finally:
if fileId is not None:
self.close(treeId, fileId)
self.disconnectTree(treeId)
return True
def storeFile(self, shareName, path, callback, mode = FILE_OVERWRITE_IF, offset = 0, password = None, shareAccessMode = FILE_SHARE_WRITE):
# 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:
fileId = self.create(treeId, path, FILE_WRITE_DATA, shareAccessMode, FILE_NON_DIRECTORY_FILE, mode, 0)
finished = False
writeOffset = offset
while not finished:
data = callback(self._Connection['MaxWriteSize'])
if len(data) == 0:
break
written = self.write(treeId, fileId, data, writeOffset, len(data))
writeOffset += written
finally:
if fileId is not None:
self.close(treeId, fileId)
self.disconnectTree(treeId)
def printSources(self, hierarchy, commonprefix):
sorteditems = sorted(hierarchy.items(), key=lambda a: a[0].lower())
# First folders, then files
for key, value in sorteditems:
if SCons.Util.is_Dict(value):
self.file.write('\t\t\t<Filter\n'
'\t\t\t\tName="%s"\n'
'\t\t\t\tFilter="">\n' % (key))
self.printSources(value, commonprefix)
self.file.write('\t\t\t</Filter>\n')
for key, value in sorteditems:
if SCons.Util.is_String(value):
file = value
if commonprefix:
file = os.path.join(commonprefix, value)
file = os.path.normpath(file)
self.file.write('\t\t\t<File\n'
'\t\t\t\tRelativePath="%s">\n'
'\t\t\t</File>\n' % (file))
def printSources(self, hierarchy, kind, commonprefix, filter_name):
keywords = {'Source Files': 'ClCompile',
'Header Files': 'ClInclude',
'Local Headers': 'ClInclude',
'Resource Files': 'None',
'Other Files': 'None'}
sorteditems = sorted(hierarchy.items(), key = lambda a: a[0].lower())
# First folders, then files
for key, value in sorteditems:
if SCons.Util.is_Dict(value):
self.printSources(value, kind, commonprefix, filter_name + '\\' + key)
for key, value in sorteditems:
if SCons.Util.is_String(value):
file = value
if commonprefix:
file = os.path.join(commonprefix, value)
file = os.path.normpath(file)
self.file.write('\t\t<%s Include="%s" />\n' % (keywords[kind], file))
self.filters_file.write('\t\t<%s Include="%s">\n'
'\t\t\t<Filter>%s</Filter>\n'
'\t\t</%s>\n' % (keywords[kind], file, filter_name, keywords[kind]))
def checkIntegrity():
"""
Checks integrity of code files during the unhandled exceptions
"""
logger.debug("running code integrity check")
retVal = True
for checksum, _ in (re.split(r'\s+', _) for _ in getFileItems(paths.CHECKSUM_MD5)):
path = os.path.normpath(os.path.join(paths.SQLMAP_ROOT_PATH, _))
if not os.path.isfile(path):
logger.error("missing file detected '%s'" % path)
retVal = False
elif hashlib.md5(open(path, 'rb').read()).hexdigest() != checksum:
logger.error("wrong checksum of file '%s' detected" % path)
retVal = False
return retVal
def printSources(self, hierarchy, commonprefix):
sorteditems = sorted(hierarchy.items(), key=lambda a: a[0].lower())
# First folders, then files
for key, value in sorteditems:
if SCons.Util.is_Dict(value):
self.file.write('\t\t\t<Filter\n'
'\t\t\t\tName="%s"\n'
'\t\t\t\tFilter="">\n' % (key))
self.printSources(value, commonprefix)
self.file.write('\t\t\t</Filter>\n')
for key, value in sorteditems:
if SCons.Util.is_String(value):
file = value
if commonprefix:
file = os.path.join(commonprefix, value)
file = os.path.normpath(file)
self.file.write('\t\t\t<File\n'
'\t\t\t\tRelativePath="%s">\n'
'\t\t\t</File>\n' % (file))
def printSources(self, hierarchy, kind, commonprefix, filter_name):
keywords = {'Source Files': 'ClCompile',
'Header Files': 'ClInclude',
'Local Headers': 'ClInclude',
'Resource Files': 'None',
'Other Files': 'None'}
sorteditems = sorted(hierarchy.items(), key = lambda a: a[0].lower())
# First folders, then files
for key, value in sorteditems:
if SCons.Util.is_Dict(value):
self.printSources(value, kind, commonprefix, filter_name + '\\' + key)
for key, value in sorteditems:
if SCons.Util.is_String(value):
file = value
if commonprefix:
file = os.path.join(commonprefix, value)
file = os.path.normpath(file)
self.file.write('\t\t<%s Include="%s" />\n' % (keywords[kind], file))
self.filters_file.write('\t\t<%s Include="%s">\n'
'\t\t\t<Filter>%s</Filter>\n'
'\t\t</%s>\n' % (keywords[kind], file, filter_name, keywords[kind]))
def mkdir(self, shareName, pathName, password = None):
# ToDo: Handle situations where share is password protected
pathName = string.replace(pathName,'/', '\\')
pathName = ntpath.normpath(pathName)
if len(pathName) > 0 and pathName[0] == '\\':
pathName = pathName[1:]
treeId = self.connectTree(shareName)
fileId = None
try:
fileId = self.create(treeId, pathName,GENERIC_ALL ,FILE_SHARE_READ | FILE_SHARE_WRITE |FILE_SHARE_DELETE, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, FILE_CREATE, 0)
finally:
if fileId is not None:
self.close(treeId, fileId)
self.disconnectTree(treeId)
return True
def rmdir(self, shareName, pathName, password = None):
# ToDo: Handle situations where share is password protected
pathName = string.replace(pathName,'/', '\\')
pathName = ntpath.normpath(pathName)
if len(pathName) > 0 and pathName[0] == '\\':
pathName = pathName[1:]
treeId = self.connectTree(shareName)
fileId = None
try:
fileId = self.create(treeId, pathName, desiredAccess=DELETE | FILE_READ_ATTRIBUTES | SYNCHRONIZE,
shareMode=FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
creationOptions=FILE_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT,
creationDisposition=FILE_OPEN, fileAttributes=0)
from impacket import smb
delete_req = smb.SMBSetFileDispositionInfo()
delete_req['DeletePending'] = True
self.setInfo(treeId, fileId, inputBlob=delete_req, fileInfoClass=SMB2_FILE_DISPOSITION_INFO)
finally:
if fileId is not None:
self.close(treeId, fileId)
self.disconnectTree(treeId)
return True
def remove(self, shareName, pathName, password = None):
# ToDo: Handle situations where share is password protected
pathName = string.replace(pathName,'/', '\\')
pathName = ntpath.normpath(pathName)
if len(pathName) > 0 and pathName[0] == '\\':
pathName = pathName[1:]
treeId = self.connectTree(shareName)
fileId = None
try:
fileId = self.create(treeId, pathName,DELETE | FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_NON_DIRECTORY_FILE | FILE_DELETE_ON_CLOSE, FILE_OPEN, 0)
finally:
if fileId is not None:
self.close(treeId, fileId)
self.disconnectTree(treeId)
return True
def storeFile(self, shareName, path, callback, mode = FILE_OVERWRITE_IF, offset = 0, password = None, shareAccessMode = FILE_SHARE_WRITE):
# 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:
fileId = self.create(treeId, path, FILE_WRITE_DATA, shareAccessMode, FILE_NON_DIRECTORY_FILE, mode, 0)
finished = False
writeOffset = offset
while not finished:
data = callback(self._Connection['MaxWriteSize'])
if len(data) == 0:
break
written = self.write(treeId, fileId, data, writeOffset, len(data))
writeOffset += written
finally:
if fileId is not None:
self.close(treeId, fileId)
self.disconnectTree(treeId)
def do_get(self, src_path):
try:
import ntpath
newPath = ntpath.normpath(ntpath.join(self.__pwd, src_path))
drive, tail = ntpath.splitdrive(newPath)
filename = ntpath.basename(tail)
fh = open(filename,'wb')
logging.info("Downloading %s\\%s" % (drive, tail))
self.__transferClient.getFile(drive[:-1]+'$', tail, fh.write)
fh.close()
except Exception, e:
logging.error(str(e))
os.remove(filename)
pass
def do_cd(self, s):
self.execute_remote('cd ' + s)
if len(self.__outputBuffer.strip('\r\n')) > 0:
print self.__outputBuffer
self.__outputBuffer = ''
else:
self.__pwd = ntpath.normpath(ntpath.join(self.__pwd, s))
self.execute_remote('cd ')
self.__pwd = self.__outputBuffer.strip('\r\n')
self.prompt = self.__pwd + '>'
self.__outputBuffer = ''
def do_cd(self, line):
p = string.replace(line,'/','\\')
oldpwd = self.pwd
newPath = ntpath.normpath(ntpath.join(self.pwd,p))
if newPath == self.pwd:
# Nothing changed
return
common = ntpath.commonprefix([newPath,oldpwd])
if common == oldpwd:
res = self.findPathName(ntpath.normpath(p))
else:
res = self.findPathName(newPath)
if res is None:
logging.error("Directory not found")
self.pwd = oldpwd
return
if res.isDirectory() == 0:
logging.error("Not a directory!")
self.pwd = oldpwd
return
else:
self.currentINode = res
self.do_ls('', False)
self.pwd = ntpath.join(self.pwd,p)
self.pwd = ntpath.normpath(self.pwd)
self.prompt = self.pwd + '>'
def do_get(self, line):
pathName = string.replace(line,'/','\\')
pathName = ntpath.normpath(ntpath.join(self.pwd,pathName))
fh = open(ntpath.basename(pathName),"wb")
self.do_cat(line, command = fh.write)
fh.close()
def do_cd(self, s):
self.execute_remote('cd ' + s)
if len(self.__outputBuffer.strip('\r\n')) > 0:
print self.__outputBuffer.decode(CODEC)
self.__outputBuffer = ''
else:
self.__pwd = ntpath.normpath(ntpath.join(self.__pwd, s.decode(sys.stdin.encoding)))
self.execute_remote('cd ')
self.__pwd = self.__outputBuffer.strip('\r\n').decode(CODEC)
self.prompt = unicode(self.__pwd + '>').encode(sys.stdout.encoding)
self.__outputBuffer = ''
def rename(self, shareName, oldPath, newPath):
oldPath = string.replace(oldPath,'/', '\\')
oldPath = ntpath.normpath(oldPath)
if len(oldPath) > 0 and oldPath[0] == '\\':
oldPath = oldPath[1:]
newPath = string.replace(newPath,'/', '\\')
newPath = ntpath.normpath(newPath)
if len(newPath) > 0 and newPath[0] == '\\':
newPath = newPath[1:]
treeId = self.connectTree(shareName)
fileId = None
try:
fileId = self.create(treeId, oldPath, MAXIMUM_ALLOWED ,FILE_SHARE_READ | FILE_SHARE_WRITE |FILE_SHARE_DELETE, 0x200020, FILE_OPEN, 0)
renameReq = FILE_RENAME_INFORMATION_TYPE_2()
renameReq['ReplaceIfExists'] = 1
renameReq['RootDirectory'] = '\x00'*8
renameReq['FileNameLength'] = len(newPath)*2
renameReq['FileName'] = newPath.encode('utf-16le')
self.setInfo(treeId, fileId, renameReq, infoType = SMB2_0_INFO_FILE, fileInfoClass = SMB2_FILE_RENAME_INFO)
finally:
if fileId is not None:
self.close(treeId, fileId)
self.disconnectTree(treeId)
return True