Python ntpath.basename() Examples

The following are 30 code examples of ntpath.basename(). 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: getsids.py    From aumfor with GNU General Public License v3.0 7 votes vote down vote up
def lookup_user_sids(self):

        regapi = registryapi.RegistryApi(self._config)
        regapi.set_current("hklm")

        key = "Microsoft\\Windows NT\\CurrentVersion\\ProfileList"
        val = "ProfileImagePath"

        sids = {}

        for subkey in regapi.reg_get_all_subkeys(None, key = key):
            sid = str(subkey.Name)
            path = regapi.reg_get_value(None, key = "", value = val, given_root = subkey)
            if path:
                path = str(path).replace("\x00", "")
                user = ntpath.basename(path)
                sids[sid] = user

        return sids 
Example #2
Source File: visualizer.py    From Talking-Face-Generation-DAVS with MIT License 6 votes vote down vote up
def save_images(self, webpage, visuals, image_path):
        image_dir = webpage.get_image_dir()
        short_path = ntpath.basename(image_path[0])
        name = os.path.splitext(short_path)[0]

        webpage.add_header(name)
        ims = []
        txts = []
        links = []

        for label, image_numpy in visuals.items():
            image_name = '%s_%s.png' % (name, label)
            save_path = os.path.join(image_dir, image_name)
            util.save_image(image_numpy, save_path)

            ims.append(image_name)
            txts.append(label)
            links.append(image_name)
        webpage.add_images(ims, txts, links, width=self.win_size) 
Example #3
Source File: config.py    From mackrl with Apache License 2.0 6 votes vote down vote up
def get_cfg(existing_cfg, _log):
    """

    """
    _sanity_check(existing_cfg, _log)
    import ntpath, os, ruamel.yaml as yaml
    with open(os.path.join(os.path.dirname(__file__), "{}.yml".format(ntpath.basename(__file__).split(".")[0])), 'r') as stream:
        try:
            ret = yaml.load(stream, Loader=yaml.Loader)
        except yaml.YAMLError as exc:
            assert False, "Default config yaml for '{}' not found!".format(os.path.splitext(__file__)[0])

    if not "batch_size_run" in ret:
        ret["batch_size_run"] = ret["batch_size"]

    if not "runner_test_batch_size" in ret:
        ret["runner_test_batch_size"] = ret["batch_size_run"]

    if not "name" in ret:
        ret["name"] = ntpath.basename(__file__).split(".")[0]

    return ret 
Example #4
Source File: gftools-check-name.py    From gftools with Apache License 2.0 6 votes vote down vote up
def main():
  args = parser.parse_args()

  rows = []
  for font_filename in args.fonts:
    font = TTFont(font_filename)
    for field in font['name'].names:
      enc = field.getEncoding()
      rows.append([
        ('Font', ntpath.basename(font_filename)),
        ('platformID', field.platformID),
        ('encodingID', field.platEncID),
        ('languageID', field.langID),
        ('nameID', field.nameID),
        ('nameString', field.toUnicode()),
      ])

  if args.csv:
    printInfo(rows, save=True)
  else:
    printInfo(rows) 
Example #5
Source File: config.py    From mackrl with Apache License 2.0 6 votes vote down vote up
def get_cfg(existing_cfg, _log):
    """

    """
    _sanity_check(existing_cfg, _log)
    import ntpath, os, ruamel.yaml as yaml
    with open(os.path.join(os.path.dirname(__file__), "{}.yml".format(ntpath.basename(__file__).split(".")[0])), 'r') as stream:
        try:
            ret = yaml.load(stream, Loader=yaml.Loader)
        except yaml.YAMLError as exc:
            assert False, "Default config yaml for '{}' not found!".format(os.path.splitext(__file__)[0])

    if not "batch_size_run" in ret:
        ret["batch_size_run"] = ret["batch_size"]

    if not "runner_test_batch_size" in ret:
        ret["runner_test_batch_size"] = ret["batch_size_run"]

    if not "name" in ret:
        ret["name"] = ntpath.basename(__file__).split(".")[0]

    return ret 
Example #6
Source File: config.py    From mackrl with Apache License 2.0 6 votes vote down vote up
def get_cfg(existing_cfg, _log):
    """
    generates
    """
    _sanity_check(existing_cfg, _log)
    import ntpath, os, ruamel.yaml as yaml
    with open(os.path.join(os.path.dirname(__file__), "{}.yml".format(ntpath.basename(__file__).split(".")[0])),
              'r') as stream:
        try:
            ret = yaml.load(stream, Loader=yaml.Loader)
        except yaml.YAMLError as exc:
            assert "Default config yaml for '{}' not found!".format(os.path.splitext(__file__)[0])

    #if ret["coma_critic_use_sampling"] and "coma_critic_sample_size" not in ret and hasattr(ret, "batch_size_run"):
    #    ret["coma_critic_sample_size"] = ret["batch_size_run"] * 50
    return ret 
Example #7
Source File: visualiser.py    From Attention-Gated-Networks with MIT License 6 votes vote down vote up
def save_images(self, webpage, visuals, image_path):
        image_dir = webpage.get_image_dir()
        short_path = ntpath.basename(image_path[0])
        name = os.path.splitext(short_path)[0]

        webpage.add_header(name)
        ims = []
        txts = []
        links = []

        for label, image_numpy in visuals.items():
            image_name = '%s_%s.png' % (name, label)
            save_path = os.path.join(image_dir, image_name)
            util.save_image(image_numpy, save_path)

            ims.append(image_name)
            txts.append(label)
            links.append(image_name)
        webpage.add_images(ims, txts, links, width=self.win_size) 
Example #8
Source File: config.py    From mackrl with Apache License 2.0 6 votes vote down vote up
def get_cfg(existing_cfg, _log):
    """

    """
    _sanity_check(existing_cfg, _log)
    import ntpath, os, ruamel.yaml as yaml
    with open(os.path.join(os.path.dirname(__file__), "{}.yml".format(ntpath.basename(__file__).split(".")[0])), 'r') as stream:
        try:
            ret = yaml.load(stream, Loader=yaml.Loader)
        except yaml.YAMLError as exc:
            assert False, "Default config yaml for '{}' not found!".format(os.path.splitext(__file__)[0])

    if not "batch_size_run" in ret:
        ret["batch_size_run"] = ret["batch_size"]

    if not "runner_test_batch_size" in ret:
        ret["runner_test_batch_size"] = ret["batch_size_run"]

    if not "name" in ret:
        ret["name"] = ntpath.basename(__file__).split(".")[0]

    return ret 
Example #9
Source File: config.py    From mackrl with Apache License 2.0 6 votes vote down vote up
def get_cfg(existing_cfg, _log):
    """
    generates
    """
    _sanity_check(existing_cfg, _log)
    import ntpath, os, ruamel.yaml as yaml
    with open(os.path.join(os.path.dirname(__file__), "{}.yml".format(ntpath.basename(__file__).split(".")[0])),
              'r') as stream:
        try:
            ret = yaml.load(stream, Loader=yaml.Loader)
        except yaml.YAMLError as exc:
            assert "Default config yaml for '{}' not found!".format(os.path.splitext(__file__)[0])

    if ret["coma_critic_use_sampling"] and "coma_critic_sample_size" not in ret and hasattr(ret, "batch_size_run"):
        ret["coma_critic_sample_size"] = ret["batch_size_run"] * 50
    return ret 
Example #10
Source File: gftools-nametable-from-filename.py    From gftools with Apache License 2.0 6 votes vote down vote up
def main():
  args = parser.parse_args()

  for font_path in args.fonts:
    nametable = nametable_from_filename(font_path)
    font = TTFont(font_path)
    font_filename = ntpath.basename(font_path)

    font['name'] = nametable
    style = font_filename[:-4].split('-')[-1]
    font['OS/2'].usWeightClass = set_usWeightClass(style)
    font['OS/2'].fsSelection = set_fsSelection(font['OS/2'].fsSelection, style)
    win_style = font['name'].getName(2, 3, 1, 1033).string.decode('utf_16_be')
    font['head'].macStyle = set_macStyle(win_style)

    font.save(font_path + '.fix')
    print('font saved %s.fix' % font_path) 
Example #11
Source File: config.py    From mackrl with Apache License 2.0 6 votes vote down vote up
def get_cfg(existing_cfg, _log):
    """

    """
    _sanity_check(existing_cfg, _log)
    import ntpath, os, yaml
    with open(os.path.join(os.path.dirname(__file__), "{}.yml".format(ntpath.basename(__file__).split(".")[0])), 'r') as stream:
        try:
            ret = yaml.load(stream)
        except yaml.YAMLError as exc:
            assert False, "Default config yaml for '{}' not found!".format(os.path.splitext(__file__)[0])

    if not "batch_size_run" in ret:
        ret["batch_size_run"] = ret["batch_size"]

    if not "runner_test_batch_size" in ret:
        ret["runner_test_batch_size"] = ret["batch_size_run"]

    if not "name" in ret:
        ret["name"] = ntpath.basename(os.path.dirname(__file__))

    return ret 
Example #12
Source File: browserhooks.py    From volatility-browserhooks with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def generator(self, data):

        for process, module, hook in data:
            procname = "N/A"
            pid = -1
            addr_base = 0

            for n, info in enumerate(hook.disassembled_hops):
                (address, data) = info
                addr_base = vad_ck().get_vad_base(process, address)
                procname = str(process.ImageFileName)
                pid = int(process.UniqueProcessId)

                yield (0, [str(hook.Type),
                    procname,
                    pid,
                    str(module.BaseDllName or '') or ntpath.basename(str(module.FullDllName or '')),
                    Address(module.DllBase),
                    module.DllBase + module.SizeOfImage,
                    str(hook.Detail),
                    Address(hook.hook_address),
                    Address(addr_base),
                    str(hook.HookModule),
                    Address(address),
                    Bytes(data)]) 
Example #13
Source File: evtlogs.py    From aumfor with GNU General Public License v3.0 6 votes vote down vote up
def render_text(self, outfd, data):
        if self._config.DUMP_DIR == None:
            debug.error("Please specify a dump directory (--dump-dir)")
        if not os.path.isdir(self._config.DUMP_DIR):
            debug.error(self._config.DUMP_DIR + " is not a directory")

        for name, buf in data: 
            ## We can use the ntpath module instead of manually replacing the slashes
            ofname = ntpath.basename(name)
            
            ## Dump the raw event log so it can be parsed with other tools
            if self._config.SAVE_EVT:
                fh = open(os.path.join(self._config.DUMP_DIR, ofname), 'wb')
                fh.write(buf)
                fh.close()
                outfd.write('Saved raw .evt file to {0}\n'.format(ofname))
            
            ## Now dump the parsed, pipe-delimited event records to a file
            ofname = ofname.replace(".evt", ".txt")
            fh = open(os.path.join(self._config.DUMP_DIR, ofname), 'wb')
            for fields in self.parse_evt_info(name, buf):
                fh.write('|'.join(fields) + "\n")    
            fh.close()
            outfd.write('Parsed data sent to {0}\n'.format(ofname)) 
Example #14
Source File: evtlogs.py    From aumfor with GNU General Public License v3.0 6 votes vote down vote up
def generator(self, data):
        if self._config.DUMP_DIR and not self._config.SAVE_EVT:
            debug.error("Please add --save-evt flag to dump EVT files")
        if self._config.SAVE_EVT and self._config.DUMP_DIR == None:
            debug.error("Please specify a dump directory (--dump-dir)")
        if self._config.SAVE_EVT and not os.path.isdir(self._config.DUMP_DIR):
            debug.error(self._config.DUMP_DIR + " is not a directory")

        for name, buf in data:
            ## Dump the raw event log so it can be parsed with other tools
            if self._config.SAVE_EVT:
                ofname = ntpath.basename(name)
                fh = open(os.path.join(self._config.DUMP_DIR, ofname), 'wb')
                fh.write(buf)
                fh.close()
                print 'Saved raw .evt file to {0}'.format(ofname)
            for fields in self.parse_evt_info(name, buf):
                yield (0, [str(fields[0]), str(fields[1]), str(fields[2]), str(fields[3]), str(fields[4]), str(fields[5]), str(fields[6])]) 
Example #15
Source File: visualizer.py    From Recycle-GAN with MIT License 6 votes vote down vote up
def save_images(self, webpage, visuals, image_path):
        image_dir = webpage.get_image_dir()
        short_path = ntpath.basename(image_path[0])
        name = os.path.splitext(short_path)[0]

        webpage.add_header(name)
        ims = []
        txts = []
        links = []

        for label, image_numpy in visuals.items():
            image_name = '%s_%s.png' % (name, label)
            save_path = os.path.join(image_dir, image_name)
            util.save_image(image_numpy, save_path)

            ims.append(image_name)
            txts.append(label)
            links.append(image_name)
        webpage.add_images(ims, txts, links, width=self.win_size) 
Example #16
Source File: mspdb.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def FetchPDBFile(self):
        # Ensure the pdb filename has the correct extension.
        pdb_filename = self.plugin_args.pdb_filename
        guid = self.plugin_args.guid

        if not pdb_filename.endswith(".pdb"):
            pdb_filename += ".pdb"

        for url in self.SYM_URLS:
            basename = ntpath.splitext(pdb_filename)[0]
            try:
                return self.DownloadUncompressedPDBFile(
                    url, pdb_filename, guid, basename)
            except urllib.error.HTTPError:
                return self.DownloadCompressedPDBFile(
                    url, pdb_filename, guid, basename) 
Example #17
Source File: visualizer.py    From iSketchNFill with GNU General Public License v3.0 6 votes vote down vote up
def save_images(self, webpage, visuals, image_path):
        image_dir = webpage.get_image_dir()
        short_path = ntpath.basename(image_path[0])
        class_info = image_path[0].split('/')[ len( image_path[0].split('/')) -2 ]
        name = class_info + '_' +  os.path.splitext(short_path)[0]

        webpage.add_header(name)
        ims = []
        txts = []
        links = []

        for label, image_numpy in visuals.items():
            image_name = '%s_%s.png' % (name, label)
            save_path = os.path.join(image_dir, image_name)
            util.save_image(image_numpy, save_path)

            ims.append(image_name)
            txts.append(label)
            links.append(image_name)
        webpage.add_images(ims, txts, links, width=self.win_size) 
Example #18
Source File: visualizer.py    From DepthAwareCNN with MIT License 6 votes vote down vote up
def save_images(self, webpage, visuals, image_path):
        image_dir = webpage.get_image_dir()
        short_path = ntpath.basename(image_path[0])
        name = os.path.splitext(short_path)[0]

        webpage.add_header(name)
        ims = []
        txts = []
        links = []

        for label, image_numpy in visuals.items():
            image_name = '%s_%s.jpg' % (name, label)
            save_path = os.path.join(image_dir, image_name)
            util.save_image(image_numpy, save_path)

            ims.append(image_name)
            txts.append(label)
            links.append(image_name)
        webpage.add_images(ims, txts, links, width=self.win_size) 
Example #19
Source File: winregistry.py    From cracke-dit with MIT License 6 votes vote down vote up
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 #20
Source File: winregistry.py    From CVE-2017-7494 with GNU General Public License v3.0 6 votes vote down vote up
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 #21
Source File: config.py    From mackrl with Apache License 2.0 6 votes vote down vote up
def get_cfg(existing_cfg, _log):
    """

    """
    _sanity_check(existing_cfg, _log)
    import ntpath, os, yaml
    with open(os.path.join(os.path.dirname(__file__), "{}.yml".format(ntpath.basename(__file__).split(".")[0])), 'r') as stream:
        try:
            ret = yaml.load(stream)
        except yaml.YAMLError as exc:
            assert False, "Default config yaml for '{}' not found!".format(os.path.splitext(__file__)[0])

    if not "batch_size_run" in ret:
        ret["batch_size_run"] = ret["batch_size"]

    if not "runner_test_batch_size" in ret:
        ret["runner_test_batch_size"] = ret["batch_size_run"]

    if not "name" in ret:
        ret["name"] = ntpath.basename(os.path.dirname(__file__))

    return ret 
Example #22
Source File: attacks.py    From aletheia with MIT License 5 votes vote down vote up
def extra_size(filename):
    print("WARNING! not implemented")

    name=ntpath.basename(filename)
    I = imread(filename)

    imsave(tempfile.gettempdir()+'/'+name, I)
    return 0


# -- EXIF --

# {{{ exif() 
Example #23
Source File: IOUevaluater.py    From ScanSSD with MIT License 5 votes vote down vote up
def  write_html(gtFile,resultsFile,info,scores,destFile):
    
		destFile.write('<html>')
		destFile.write('<head><link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"><link href="/static/css/bootstrap.min.css" rel="stylesheet"></head>')
		destFile.write('<body>')
		#writeCSS(destFile)
		destFile.write ("<blockquote><b>CROHME 2019</b> <h1> Formula Detection Results ( TASK 3 )</h1><hr>")
		destFile.write("<b>Submitted Files</b><ul><li><b>Output:</b> "+ ntpath.basename(resultsFile) +"</li>")    		
		destFile.write ("<li><b>Ground-truth:</b> " + ntpath.basename(gtFile) + "</li></ul>")
		if info['allGTbox'] == 0:
			sys.stderr.write("Error : no sample in this GT list !\n")
			exit(-1) 
        #all detection and gt boxes 
		destFile.write ("<p><b> Number of ground truth bounding boxes: </b>" + str(info['allGTbox']) + "<br /><b> Number of detected bounding boxes: </b>" + str(info['allDet']))            
		destFile.write ("<hr>")
        #coarse results
		destFile.write ("<p><b> **** Coarse Detection Results (IOU>0.5) ****</b><br />")
		destFile.write ("<ul><li><b>"+str(scores['coarse_f']) + "</b> F-score</li>")
		destFile.write ("<li>"+str(scores['coarse_pre']) + " Precision</li>")
		destFile.write ("<li>"+str(scores['coarse_rec']) + " Recall</li></ul>")
		destFile.write ("<b>" + str(info['correctDet_c']) + "</b> Number of correctly detected bounding boxes</p>")
		destFile.write ("<hr>")
        #fine results
		destFile.write ("<p><b> **** Fine Detection Results (IOU>0.75) ****</b><br />")
		destFile.write ("<ul><li><b>"+str(scores['fine_f']) + "</b> F-score</li>")
		destFile.write ("<li>"+str(scores['fine_pre']) + " Precision</li>")
		destFile.write ("<li>"+str(scores['fine_rec']) + " Recall</li></ul>")
		destFile.write ("<b>" + str(info['correctDet_f']) + "</b> Number of correctly detected bounding boxes</p>")
		destFile.write ("<hr>")
		destFile.write('</body>')
		destFile.write('</html>') 
Example #24
Source File: amcache_raw_hive.py    From appcompatprocessor with Apache License 2.0 5 votes vote down vote up
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 
Example #25
Source File: amcache_miracquisition.py    From appcompatprocessor with Apache License 2.0 5 votes vote down vote up
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 
Example #26
Source File: diff.py    From dyc with MIT License 5 votes vote down vote up
def __clean(self, patch, diff):
        """Returns a clean dict of a path"""
        result = {}
        result['additions'] = self.__additions(
            self.__pack(patch.split('\n')), diff.a_path
        )  # [{hunk: (start, end), patch:}]
        result['plain'] = patch
        result['diff'] = diff
        result['name'] = ntpath.basename(diff.a_path)
        result['path'] = diff.a_path
        return result 
Example #27
Source File: visualizer.py    From EvolutionaryGAN-pytorch with MIT License 5 votes vote down vote up
def save_images(webpage, visuals, image_path, aspect_ratio=1.0, width=256):
    """Save images to the disk.

    Parameters:
        webpage (the HTML class) -- the HTML webpage class that stores these imaegs (see html.py for more details)
        visuals (OrderedDict)    -- an ordered dictionary that stores (name, images (either tensor or numpy) ) pairs
        image_path (str)         -- the string is used to create image paths
        aspect_ratio (float)     -- the aspect ratio of saved images
        width (int)              -- the images will be resized to width x width

    This function will save images stored in 'visuals' to the HTML file specified by 'webpage'.
    """
    image_dir = webpage.get_image_dir()
    short_path = ntpath.basename(image_path[0])
    name = os.path.splitext(short_path)[0]

    webpage.add_header(name)
    ims, txts, links = [], [], []

    for label, im_data in visuals.items():
        im = util.tensor2im(im_data)
        image_name = '%s_%s.png' % (name, label)
        save_path = os.path.join(image_dir, image_name)
        h, w, _ = im.shape
        if aspect_ratio > 1.0:
            im = imresize(im, (h, int(w * aspect_ratio)), interp='bicubic')
        if aspect_ratio < 1.0:
            im = imresize(im, (int(h / aspect_ratio), w), interp='bicubic')
        util.save_image(im, save_path)

        ims.append(image_name)
        txts.append(label)
        links.append(image_name)
    webpage.add_images(ims, txts, links, width=width) 
Example #28
Source File: smb3.py    From cracke-dit with MIT License 5 votes vote down vote up
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 #29
Source File: base.py    From zou with GNU Affero General Public License v3.0 5 votes vote down vote up
def upload_file(self, path, file_path, code=201):
        """
        Upload a file at given path. File data are sent in the request body.
        """
        file_content = open(file_path, "rb")
        file_name = ntpath.basename(file_path)
        response = self.app.post(
            path,
            data={"file": (file_content, file_name)},
            headers=self.base_headers
        )
        self.assertEqual(response.status_code, code)
        return response.data 
Example #30
Source File: object.py    From simpleSB with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def sendFile(self, to, path, file_name=''):
        if file_name == '':
            file_name = ntpath.basename(path)
        file_size = len(open(path, 'rb').read())
        objectId = self.sendMessage(to=to, text=None, contentMetadata={'FILE_NAME': str(file_name),'FILE_SIZE': str(file_size)}, contentType = 14).id
        files = {'file': open(path, 'rb')}
        data = {'params': self.genOBSParams({'name': file_name,'oid': objectId,'size': file_size,'type': 'file'})}
        r = self.server.postContent(self.server.LINE_OBS_DOMAIN + '/talk/m/upload.nhn', data=data, files=files)
        if r.status_code != 201:
            raise Exception('Upload file failure.')
        return True