def modify_sfxfile(fout, filename, on_wav_file): with rfactortools.open_read(filename) as fin: lines = fin.read().splitlines() for orig_line in lines: m = comment_regex.match(orig_line) if m: comment = m.group(2) line = m.group(1) else: comment = "" line = orig_line suffix = comment m = wav1_regex.match(line) if m: wav = on_wav_file(rfactortools.nt2posixpath(m.group(3))) if wav is not None: wav = ntpath.normpath(wav) else: wav = m.group(3) fout.write("%s=%s,%s%s\n" % (m.group(1), m.group(2), wav, suffix)) else: m = wav2_regex.match(line) if m: wav = on_wav_file(rfactortools.nt2posixpath(m.group(2))) if wav is not None: wav = ntpath.normpath(wav) else: wav = m.group(2) fout.write("%s=%s%s\n" % (m.group(1), wav, suffix)) else: fout.write(orig_line) fout.write("\n")
def main(): if len(sys.argv) <= 1 or sys.argv[1] == '--help': print usage_text return with open(sys.argv[1]) as f: config = json.load(f) basedir = os.path.abspath(config['basedir']) os.chdir(basedir) output_directories = set() output_files = [] for fileset in config['files']: os.chdir(basedir) os.chdir(fileset['source']) for pattern in fileset['patterns']: files = ant_glob(pattern) for filename in files: frompath = ntpath.normpath(ntpath.join(fileset['source'], filename)) topath = ntpath.normpath(ntpath.join(fileset['target'], filename)) output_directories.update(topath[:index+1] for (index, ch) in enumerate(topath) if ch=='\\') output_files.append((frompath, topath)) print " <ItemGroup>" for dirname in sorted(output_directories): print " <Folder Include={0} />".format(quoteattr(dirname)) print " </ItemGroup>" print " <ItemGroup>" for (frompath, topath) in output_files: print " <Content Include=\"{0}\">\n <Link>{1}</Link>\n </Content>".format(escape(frompath), escape(topath)) print " </ItemGroup>"
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 gen_webv_fake_data(expdic=settings.CREATE_D, type_exp='chantigap', pseudotype_dic=settings.PSEUDO_D, id='MAC07', wave_dic=None, outpath='TEST', iswin=False): """ Generates a WEPV folder with data of the type/kind/size specs anticipated. Files in the WEPV folder are made up of random bytes. @todo: fsep/code placement, generic settings, os. selfchecks """ # generate time and date strings (based upon dt.datetime.now() datestr, timestr = fake_time() # check what kind of pseudo we need (B or A) pseudo_pre = pseudotype_dic[type_exp] pseudo = fake_pseudo(ptype=pseudo_pre) twave = fake_wave(dic=wave_dic, experiment=type_exp) wepvstring = (pseudo + '_' + twave + '_' + type_exp + '_' + datestr + '_' + timestr + '_' + id) #now let's create that dir, first simple if iswin: ntpath.normpath(outpath) else: posixpath.normpath(outpath) if not os.path.exists(outpath + os.path.sep + wepvstring): try: os.mkdir(outpath + os.path.sep + wepvstring) except OSError as exc: if exc.errno != errno.EEXIST: raise exc pass print (outpath + os.path.sep + wepvstring + " was created") else: print (outpath + os.path.sep + wepvstring + " already exists") subd = expdic[type_exp] for k, v in subd.items(): fake_file(outpath + os.path.sep + wepvstring + os.path.sep + wepvstring + '_' + k, bytesize=v)
def relntpath(path, start): import ntpath # the windows version of os.path #available in python 2.6 # return ntpath.relpath(path, start) if start == None: start = os.getcwd() path = ntpath.normpath(path) start = ntpath.normpath(start) (drivep, tailp) = ntpath.splitdrive(path) (drives, tails) = ntpath.splitdrive(start) # if one of the paths has no drive letter, treat both of them so if drivep == "" or drives == "": path = tailp start = tails elif drivep != drives: # ntpath.relpath returns error if drive letters differ, but we wont return path pathl = path.replace("/", "\\").split("\\") startl = start.replace("/", "\\").split("\\") # print "path: %s, start:%s"%(path, start ) while len(pathl) and len(startl) and pathl[0] == startl[0]: # print "removing "+pathl[0] del pathl[0] del startl[0] for i in range(len(startl)): pathl.insert(0, "..") return ntpath.join(".", *pathl)
def create_dir_hierarchy(self, file_metadata, log): """ Create a directory hierarchy :param file_metadata: :param log: :return: """ if file_metadata is None: return # The root directory doesn't have to be created if file_metadata.path == "": return # Create parents directories parent_metadata = file_metadata.parent_metadata() if parent_metadata is not None: path = ntpath.normpath(file_metadata.path) parent_path = ntpath.normpath(parent_metadata.path) if path != parent_path: self.create_dir_hierarchy(parent_metadata, log) # Create the directory itself self.fs.create_directory(file_metadata, log)
def list_path_recursive(self, host, share, pwd, wildcard, pathList, pattern, verbose): root = self.pathify(pwd) root = ntpath.normpath(root) width = 16 try: pathList[root] = self.smbconn[host].listPath(share, root) if verbose: print "\t.%s" % (root.strip("*")) if len(pathList[root]) > 2: for smbItem in pathList[root]: try: filename = smbItem.get_longname() isDir = "d" if smbItem.is_directory() > 0 else "-" filesize = smbItem.get_filesize() readonly = "w" if smbItem.is_readonly() > 0 else "r" date = time.ctime(float(smbItem.get_mtime_epoch())) if smbItem.is_directory() <= 0: fileMatch = re.search(pattern.lower(), filename.lower()) if fileMatch: dlThis = "%s\\%s/%s" % (share, pwd, filename) dlThis = dlThis.replace("/", "\\") print "\t[+] Match found! Downloading: %s" % (ntpath.normpath(dlThis)) self.download_file(host, dlThis, False) if verbose: print "\t%s%s--%s--%s-- %s %s\t%s" % ( isDir, readonly, readonly, readonly, str(filesize).rjust(width), date, filename, ) except SessionError as e: print "[!]", e continue except Exception as e: print "[!]", e exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print (exc_type, fname, exc_tb.tb_lineno) sys.stdout.flush() for smbItem in pathList[root]: try: filename = smbItem.get_longname() if smbItem.is_directory() > 0 and filename != "." and filename != "..": subPath = "%s/%s" % (pwd, filename) subPath = self.pathify(subPath) pathList[subPath] = self.smbconn[host].listPath(share, subPath) if len(pathList[subPath]) > 2: self.list_path_recursive( host, share, "%s/%s" % (pwd, filename), wildcard, pathList, pattern, verbose ) except SessionError as e: continue except Exception as e: 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: if PY2: self.__pwd = ntpath.normpath(ntpath.join(self.__pwd, s.decode(sys.stdin.encoding))) 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 download_file(self, host, path, verbose=True): try: os.mkdir('files') except OSError: pass path = path.replace('/','\\') path = ntpath.normpath(path) filename = path.split('\\')[-1] share = path.split('\\')[0] path = path.replace(share, '') dlpath = ntpath.basename('%s/%s' % (os.getcwd(), '%s-%s%s' % (host, share.replace('$',''), path.replace('\\','_')))) dlpath = os.path.join('files', dlpath) if os.path.exists(dlpath): info("Continuing, already downloaded {}".format(dlpath)) return try: success('Match found! Downloading: %s' % (ntpath.normpath(dlpath))) # out = open(ntpath.basename('%s/%s' % (os.getcwd(), '%s-%s%s' % (host, share.replace('$',''), path.replace('\\','_')))),'wb') out = open(dlpath, 'wb') dlFile = self.smbconn[host].listPath(share, path) if verbose: msg = '[+] Starting download: %s (%s bytes)' % ('%s%s' % (share, path), dlFile[0].get_filesize()) if self.pattern: msg = '\t' + msg info(msg ) self.smbconn[host].getFile(share, path, out.write) if verbose: msg = '[+] File output to: %s/%s' % (os.getcwd(), ntpath.basename('%s/%s' % (os.getcwd(), '%s-%s%s' % (host, share.replace('$',''), path.replace('\\','_'))))) if self.pattern: msg = '\t'+msg info(msg ) except SessionError as e: if 'STATUS_ACCESS_DENIED' in str(e): color('[!] Error retrieving file, access denied') elif 'STATUS_INVALID_PARAMETER' in str(e): color('[!] Error retrieving file, invalid path') elif 'STATUS_SHARING_VIOLATION' in str(e): if not verbose: indent = '\t' else: indent = '' color('[!] Error retrieving file %s, sharing violation' % (indent, filename)) out.close() os.remove(ntpath.basename('%s/%s' % (os.getcwd(), '%s-%s%s' % (host, share.replace('$',''), path.replace('\\','_'))))) except Exception as e: warning('[!] Error retrieving file, unknown error') os.remove(filename) out.close() return '%s/%s' % (os.getcwd(), ntpath.basename('%s/%s' % (os.getcwd(), '%s-%s%s' % (host, share, path.replace('\\','_')))))
def AsBatch(self, expandvars=False, nodep=False): ''' :param bool expandvars: If True expand environment variables references in the returning value. If False platformize environment variables references. ''' if expandvars: result = os.path.expandvars(self.__path) elif nodep: result = ntpath.normpath(self.__path) else: result = ntpath.normpath(self.__path) result = ntpath.normcase(result) result = self._PlatformizeEnvVarsReferences(result) return result
def setupEnv(reinitialize=False): dsz.env.Set('OPS_TIME', ops.timestamp()) dsz.env.Set('OPS_DATE', ops.datestamp()) for i in flags(): if ((not dsz.env.Check(i)) or reinitialize): ops.env.set(i, False) dszflags = dsz.control.Method() dsz.control.echo.Off() if (not dsz.cmd.Run('systempaths', dsz.RUN_FLAG_RECORD)): ops.error("Could not get system paths. I'm confused. This means your OPS_TEMPDIR, OPS_WINDOWSDIR, and OPS_SYSTEMDIR environment variables are not set.") else: dsz.env.Set('OPS_TEMPDIR', ntpath.normpath(dsz.cmd.data.Get('TempDir::Location', dsz.TYPE_STRING)[0])) dsz.env.Set('OPS_WINDOWSDIR', ntpath.normpath(dsz.cmd.data.Get('WindowsDir::Location', dsz.TYPE_STRING)[0])) dsz.env.Set('OPS_SYSTEMDIR', ntpath.normpath(dsz.cmd.data.Get('SystemDir::Location', dsz.TYPE_STRING)[0])) del dszflags
def get_root_location(): basicConfig = BasicConfig.objects.all()[0] location = basicConfig.root_location if not os.path.isdir(location) or not os.path.isabs(location): root_path = commons.get_portal_parent_location() location = os.path.join(root_path, location) return normpath(location)
def _get_native_reldir(self, dospath): """Return the native dir path for a given BASIC dir path, relative to the root.""" if b'/' in dospath: # bad file number - this is what GW produces here raise error.BASICError(error.BAD_FILE_NUMBER) if not self._native_root: # this drive letter is not available (not mounted) raise error.BASICError(error.PATH_NOT_FOUND) # find starting directory if dospath and dospath[:1] == b'\\': # absolute path specified cwd = [] else: cwd = self._native_cwd.split(os.sep) # parse internal .. and . and double slashes dospath = ntpath.normpath(dospath) # parse leading . and .. and double slashes in relative path # if at root, just drop leading dots (this is what GW-BASIC does at drive root) dospath_elements = dospath.split(b'\\') while dospath_elements and dospath_elements[0] in (b'', b'.', b'..'): if dospath_elements[0] == b'..': cwd = cwd[:-1] dospath_elements = dospath_elements[1:] # prepend drive root path to allow filename matching path = os.path.join(self._native_root, *cwd) root_len = len(self._native_root) + (self._native_root[-1:] != os.sep) # find the native matches for each step in the path for dos_elem in dospath_elements: # find a matching directory for every step in the path; native_elem = self._get_native_name( path, dos_elem, defext=b'', isdir=True, create=False) # append found name to path path = os.path.join(path, native_elem) # return relative path only return path[root_len:]
def __init__(self, owner, section, key_path, default_value): values = {} for name, description, depend, rel_path in self._dirlist: values[name] = section.get(name, default=default_value) self._values = [] for name, description, depend, rel_path in self._dirlist: value = values[name] if values[name] == '<<default>>': value = rel_path if depend is not None: if values[depend] is not None: if owner.is_platform_windows: value = ntpath.join(values[depend].replace('/', '\\'), value.replace('/', '\\')) else: value = posixpath.join(values[depend], value) else: if owner.is_platform_windows: value = '<<%s>>\\%s' % (depend, value.replace('/', '\\')) else: value = '<<%s>>/%s' % (depend, value) if value is not None: if owner.is_platform_windows: value = ntpath.normpath(value.replace('/', '\\')) else: value = posixpath.normpath(value) self._values.append( _Terra3DDirectories._item(name, description, value) )
def delete_file(self, host, path, verbose=True): path = path.replace("/", "\\") path = ntpath.normpath(path) filename = path.split("\\")[-1] share = path.split("\\")[0] path = path.replace(share, "") path = path.replace(filename, "") try: self.smbconn[host].deleteFile(share, path + filename) if verbose: print "[+] File successfully deleted: %s%s%s" % (share, path, filename) except SessionError as e: if "STATUS_ACCESS_DENIED" in str(e): if verbose: print "[!] Error deleting file, access denied" elif "STATUS_INVALID_PARAMETER" in str(e): if verbose: print "[!] Error deleting file, invalid path" elif "STATUS_SHARING_VIOLATION" in str(e): if verbose: print "[!] Error retrieving file, sharing violation" else: print "[!] Error deleting file %s%s%s, unkown error" % (share, path, filename) print "[!]", e except Exception as e: print "[!] Error deleting file %s%s%s, unkown error" % (share, path, filename) print "[!]", e
def toabs(self, filename): import os,ntpath if os.path.isfile(filename): if not os.path.isabs(filename): filename=os.path.join(os.getcwd(),filename) filename=ntpath.normpath(filename) return filename
def list_path(self, host, share, path, pattern, verbose=False): pwd = self.pathify(path) width = 16 try: pathList = self.smbconn[host].listPath(share, pwd) if verbose: print '\t.%s' % (path.ljust(50)) for item in pathList: filesize = item.get_filesize() readonly = 'w' if item.is_readonly() > 0 else 'r' date = time.ctime(float(item.get_mtime_epoch())) isDir = 'd' if item.is_directory() > 0 else 'f' filename = item.get_longname() if item.is_directory() <= 0: if self.pattern: fileMatch = re.search(pattern.lower(), filename.lower()) if fileMatch: dlThis = '%s\\%s/%s' % (share, ntpath.normpath(pwd.strip('*')), filename) dlThis = dlThis.replace('/','\\') print '\t[+] Match found! Downloading: %s' % (dlThis) self.download_file(host, dlThis, False) if verbose: print '\t%s%s--%s--%s-- %s %s\t%s' % (isDir, readonly, readonly, readonly, str(filesize).rjust(width), date, filename) return True except Exception as e: return False
def dump(self, host): permissions = {} root = ntpath.normpath("\\{}".format(self.__permdir)) for share in self.__smbconnection.listShares(): share_name = share['shi1_netname'][:-1] permissions[share_name] = [] try: if self.__smbconnection.listPath(share_name, '*', settings.args.passwd): permissions[share_name].append('READ') except SessionError: pass try: if self.__smbconnection.createDirectory(share_name, root): self.__smbconnection.deleteDirectory(share_name, root) permissions[share_name].append('WRITE') except SessionError: pass print_succ('{}:{} Available shares:'.format(host, settings.args.port)) print_att('{:>15} {:>15}'.format('SHARE', 'Permissions')) print_att('{:>15} {:>15}'.format('-----', '-----------')) for share, perm in permissions.iteritems(): if not perm: print_att(u'{:>15} {:>15}'.format(share, 'NO ACCESS')) else: print_att(u'{:>15} {:>15}'.format(share, ', '.join(perm)))
def do_ls(self, wildcard, display=True): if self.loggedIn is False: LOG.error("Not logged in") return if self.tid is None: LOG.error("No share selected") return if wildcard == '': pwd = ntpath.join(self.pwd, '*') else: pwd = ntpath.join(self.pwd, wildcard) self.completion = [] directory = [] pwd = pwd.replace('/', '\\') pwd = ntpath.normpath(pwd) for f in self.smb.listPath(self.share, pwd): if display is True: print( "%crw-rw-rw- %10d %s %s" % ('d' if f.is_directory() > 0 else '-', f.get_filesize(), time.ctime(float(f.get_mtime_epoch())), f.get_longname())) self.completion.append((f.get_longname(), f.is_directory())) if f.is_directory() > 0 and "." not in f.get_longname(): directory.append(f.get_longname()) return directory
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
def test_normpath(self): tester("ntpath.normpath('A//////././//.//B')", r"A\B") tester("ntpath.normpath('A/./B')", r"A\B") tester("ntpath.normpath('A/foo/../B')", r"A\B") tester("ntpath.normpath('C:A//B')", r"C:A\B") tester("ntpath.normpath('D:A/./B')", r"D:A\B") tester("ntpath.normpath('e:A/foo/../B')", r"e:A\B") tester("ntpath.normpath('C:///A//B')", r"C:\A\B") tester("ntpath.normpath('D:///A/./B')", r"D:\A\B") tester("ntpath.normpath('e:///A/foo/../B')", r"e:\A\B") tester("ntpath.normpath('..')", r"..") tester("ntpath.normpath('.')", r".") tester("ntpath.normpath('')", r".") tester("ntpath.normpath('/')", "\\") tester("ntpath.normpath('c:/')", "c:\\") tester("ntpath.normpath('/../.././..')", "\\") tester("ntpath.normpath('c:/../../..')", "c:\\") tester("ntpath.normpath('../.././..')", r"..\..\..") tester("ntpath.normpath('K:../.././..')", r"K:..\..\..") tester("ntpath.normpath('C:////a/b')", r"C:\a\b") tester("ntpath.normpath('//machine/share//a/b')", r"\\machine\share\a\b") # Issue 5827: Make sure normpath preserves unicode for path in (u"", u".", u"/", u"\\", u"///foo/.//bar//"): self.assertTrue(isinstance(ntpath.normpath(path), unicode), "normpath() returned str instead of unicode") tester("ntpath.normpath('\\\\.\\NUL')", r"\\.\NUL") tester("ntpath.normpath('\\\\?\\D:/XY\\Z')", r"\\?\D:/XY\Z")
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'\\', '/')
def get_devices(self): self.rec_path = ntpath.normpath(self.rec_path) joined_file = exec_file + ' "' + self.rec_path + '"' + ' /L:D' print "joined_file for get_devices --> ", joined_file a = subprocess.Popen(joined_file, stdout=subprocess.PIPE) output = a.stdout.read() return output
def test_normpath(self): tester("ntpath.normpath('A//////././//.//B')", r'A\B') tester("ntpath.normpath('A/./B')", r'A\B') tester("ntpath.normpath('A/foo/../B')", r'A\B') tester("ntpath.normpath('C:A//B')", r'C:A\B') tester("ntpath.normpath('D:A/./B')", r'D:A\B') tester("ntpath.normpath('e:A/foo/../B')", r'e:A\B') tester("ntpath.normpath('C:///A//B')", r'C:\A\B') tester("ntpath.normpath('D:///A/./B')", r'D:\A\B') tester("ntpath.normpath('e:///A/foo/../B')", r'e:\A\B') tester("ntpath.normpath('..')", r'..') tester("ntpath.normpath('.')", r'.') tester("ntpath.normpath('')", r'.') tester("ntpath.normpath('/')", '\\') tester("ntpath.normpath('c:/')", 'c:\\') tester("ntpath.normpath('/../.././..')", '\\') tester("ntpath.normpath('c:/../../..')", 'c:\\') tester("ntpath.normpath('../.././..')", r'..\..\..') tester("ntpath.normpath('K:../.././..')", r'K:..\..\..') tester("ntpath.normpath('C:////a/b')", r'C:\a\b') tester("ntpath.normpath('//machine/share//a/b')", r'\\machine\share\a\b') # Issue 5827: Make sure normpath preserves unicode for path in (u'', u'.', u'/', u'\\', u'///foo/.//bar//'): self.assertTrue(isinstance(ntpath.normpath(path), unicode), 'normpath() returned str instead of unicode') tester("ntpath.normpath('\\\\.\\NUL')", r'\\.\NUL') tester("ntpath.normpath('\\\\?\\D:/XY\\Z')", r'\\?\D:/XY\Z')
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())
def download_hash_list(config, config_filename, server): """ Downloads file with indexes of file found in remote vault and return this list @param config: configparser object @param server: easywebdav object """ config.read(config_filename) save_loc = "." rem_list = config.get("RemoteFolders", "list_dir") # the file should given this code be called checksums.txt, @todo: smarter # remote = always posix remote_checksumfile = posixpath.normpath(posixpath.join(rem_list, "checksums.txt")) local_checksumfile = path.join(save_loc, "checksums.txt") # local can be 'nt' or 'posix', let's normalise stuff if myos == "nt": local_checksumfile = ntpath.normpath(local_checksumfile) elif myos == "posix": local_checksumfile = posixpath.normpath(local_checksumfile) server.download(remote_checksumfile, local_checksumfile) # curr_file = open(path.join(save_loc,'hashlist.txt')) with open(local_checksumfile, "r") as curr_file: download_list = curr_file.readlines() if DEBUG: print(download_list) download_list = [i.split() for i in download_list if not i[0] == "#"] # remove comments from list and split string md5_list = [i for i in download_list if "md" in i[0]] sha256_list = [i for i in download_list if "sha" in i[0]] return download_list, md5_list, sha256_list
def fetch_timestamps(self): self.rec_path = ntpath.normpath(self.rec_path) joined_file = exec_file + ' "' + self.rec_path + '"' + ' /I' print "joined_file for fetch_timestamps --> ", joined_file a = subprocess.Popen(joined_file, stdout=subprocess.PIPE) output = a.stdout.read() return output
def do_cd(self, s): self.execute_remote('cd ' + s) if len(self.__outputBuffer.strip('\r\n')) > 0: print(self.__outputBuffer) self.__outputBuffer = '' else: if PY2: self._pwd = ntpath.normpath(ntpath.join(self._pwd, s.decode(sys.stdin.encoding))) 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 + '>') if self.__shell_type == 'powershell': self.prompt = 'PS ' + self.prompt + ' ' self.__outputBuffer = ''
def open(self): self.get_ready() options = QFileDialog.Options() self.fileName, _ = QFileDialog.getOpenFileName( self, "QFileDialog.getOpenFileName()", "", "Images (*.png *.jpeg *.jpg *.bmp *.gif)", options=options) self.filedir = ntpath.normpath(self.fileName) self.Name = ntpath.basename(self.filedir) image = QImage(self.fileName) image.save(self.new_filedir) image.save(self.copy_filedir) img = QImage(self.copy_filedir) self.scaleFactor = 1.0 self.imageLabel.setPixmap(QPixmap.fromImage(img)) self.imageLabel.adjustSize() self.scroll_btns.setVisible(False) self.load_filters() self.saveasAct.setEnabled(True) self.saveAct.setEnabled(True) self.cancerAct.setEnabled(True) self.toolbar.setEnabled(True)
def delete_file(self, share_name, path, log): """ Delete a file. Fires True on success, raise an exception on failure. :param share_name: :param path: :param log: :return: """ http_connector = self.get_http_connector(log) full_path = self.full_path_from_sharename(share_name, path) success = yield http_connector.http_delete_file_async(full_path) if success: # # Manually update our local metadata cache # npath = ntpath.normpath(path) parent_path = ntpath.dirname(npath) _, _ = yield self.get_dir_listing_async(share_name, parent_path, log, force_update=True) defer.returnValue(success)
def setCmd(self): #need to check all parameters self.cmd = self.binaryConverter + \ " --preset-import-file " + self.profile + " " +\ "-i " + self.path + "/" + self.inputFile + " " +\ "-o " + "./output/" + self.outputFile self.cmd = ntpath.normpath(self.cmd)
def adjustDcfFileRef(self,dcf,basedir): for elem in dcf['fileRef']: 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'\\','/')
def _parse_win32(cls, volume_config, normalize): # relative paths in windows expand to include the drive, eg C:\ # so we join the first 2 parts back together to count as one mode = 'rw' def separate_next_section(volume_config): drive, tail = splitdrive(volume_config) parts = tail.split(':', 1) if drive: parts[0] = drive + parts[0] return parts parts = separate_next_section(volume_config) if len(parts) == 1: internal = parts[0] external = None else: external = parts[0] parts = separate_next_section(parts[1]) external = ntpath.normpath(external) internal = parts[0] if len(parts) > 1: if ':' in parts[1]: raise ConfigurationError( "Volume %s has incorrect format, should be " "external:internal[:mode]" % volume_config) mode = parts[1] if normalize: external = normalize_path_for_engine( external) if external else None result = cls(external, internal, mode) result.win32 = True return result
def delete_file(self, host, path, verbose=True): path = path.replace('/', '\\') path = ntpath.normpath(path) filename = path.split('\\')[-1] share = path.split('\\')[0] path = path.replace(share, '') path = path.replace(filename, '') try: self.smbconn[host].deleteFile(share, path + filename) if verbose: print( f'[+] File successfully deleted: {share}{path}{filename}') except SessionError as e: if 'STATUS_ACCESS_DENIED' in str(e): print('[!] Error deleting file, access denied') elif 'STATUS_INVALID_PARAMETER' in str(e): print('[!] Error deleting file, invalid path') elif 'STATUS_SHARING_VIOLATION' in str(e): print('[!] Error retrieving file, sharing violation') else: print( f'[!] Error deleting file {share}{path}{filename}, unkown error' ) print(f'[!], {e}') except Exception as e: print( f'[!] Error deleting file {share}{path}{filename}, unkown error' ) print(f'[!], {e}')
def rm(self, filename): self.check_share() filename = ntpath.join(self.pwd, ntpath.normpath(filename)) self.ls(filename, display=False) for identified_file, is_directory, size in self.completion: if is_directory > 0: continue filepath = ntpath.join(self.pwd, identified_file) logger.debug('Removing file %s (%d bytes)..' % (filepath, size)) try: self.smb.deleteFile(self.share, filepath) except SessionError, e: if e.getErrorCode() == nt_errors.STATUS_ACCESS_DENIED: logger.warn('Access denied to %s' % identified_file) elif e.getErrorCode() == nt_errors.STATUS_SHARING_VIOLATION: logger.warn( 'Access denied to %s due to share access flags' % identified_file) else: logger.error('Unable to remove file: %s' % (e.getErrorString(), ))
def rmdir(self, path): self.check_share() path = ntpath.join(self.pwd, ntpath.normpath(path)) self.ls(path, display=False) for identified_file, is_directory, _ in self.completion: if is_directory <= 0: continue filepath = ntpath.join(self.pwd, identified_file) logger.debug('Removing directory %s..' % filepath) try: self.smb.deleteDirectory(self.share, filepath) except SessionError, e: if e.getErrorCode() == nt_errors.STATUS_ACCESS_DENIED: logger.warn('Access denied to %s' % identified_file) elif e.getErrorCode() == nt_errors.STATUS_SHARING_VIOLATION: logger.warn( 'Access denied to %s due to share access flags' % identified_file) else: logger.error('Unable to remove directory: %s' % (e.getErrorString(), ))
def copymode(src, dst, follow_symlinks=True, **kwargs): """ Copy the permission bits from src to dst. The file contents, owner, and group are unaffected. Due to the limitations of Windows, this function only sets/unsets the dst's FILE_ATTRIBUTE_READ_ONLY flag based on what src's attribute is set to. If follow_symlinks is 'False', and both src and dst are symbolic links, copymode() will attempt to modify the mode of dst itself (rather than the file it points to). This function supports src and dst being either a local or UNC path. A relative path will be resolved based on the current working directory. :param src: The src file or directory to copy the read only flag from. :param dst: The dst file or directory to copy the read only flag to. :param follow_symlinks: Whether to copy the read only flag on the symlink or the target of the symlink. :param kwargs: Common arguments used to build the SMB Session for any UNC paths. """ src_mode = stat.S_IMODE( _get_file_stat(src, follow_symlinks, **kwargs).st_mode) norm_dst = ntpath.normpath(dst) if is_remote_path(norm_dst): read_only = not (src_mode & stat.S_IWRITE == stat.S_IWRITE and src_mode & stat.S_IREAD == stat.S_IREAD) _set_file_basic_info(dst, follow_symlinks, read_only=read_only, **kwargs) else: _local_chmod(dst, src_mode, follow_symlinks)
def get_location(self): if len(self.location) == 0: root_location = get_root_location() site_path = os.path.join(root_location, self.name) else: site_path = self.location return normpath(site_path)
def complete_files(self, text, line, begidx, endidx, include=0): ''' include means * 0: all files and directories * 1: just files * 2: just directories ''' self.smb_shell.ls(None, display=False) path = ntpath.normpath(line) if path.find('\\') < 0: items = [] if include == 1: mask = 0 else: mask = 0x010 for i in self.smb_shell.completion: if i[1] == mask or include == 0: items.append(i[0]) if text: return [ item for item in items if item.upper().startswith(text.upper()) ] else: return items
def test_realpath_curdir(self): expected = ntpath.normpath(os.getcwd()) tester("ntpath.realpath('.')", expected) tester("ntpath.realpath('./.')", expected) tester("ntpath.realpath('/'.join(['.'] * 100))", expected) tester("ntpath.realpath('.\\.')", expected) tester("ntpath.realpath('\\'.join(['.'] * 100))", expected)
def performNmapDiscover(client, ip, tmpFilename, timeout, agent_ext_dir, scanKnownPortsOnly, portstoscan, doServiceFingerprints, discoverUdpPorts, nmapLocation=None): #default port scaninng is -sS parametersList = ['-O', '-osscan-guess', '-sS'] if doServiceFingerprints: parametersList.append('-sV') if discoverUdpPorts: parametersList.append('-sU') if portstoscan: parametersList.append('-p ' + portstoscan) if scanKnownPortsOnly: parametersList.append('-F') parametersList.append('--host-timeout ' + str(timeout) + 's') parametersList.append(ip) parametersList.append('-oX ' + tmpFilename) logger.debug('start executing nmap.exe') command = NMAP_PROGRAM_NAME if nmapLocation: nmapLocation = ntpath.normpath(nmapLocation) command = ntpath.join(nmapLocation, command) command = '"' + command +'"' command = ' '.join([command] + parametersList) output = client.executeCmd(command, timeout) if output.find('is not recognized') != -1: logger.error('NMAP is not installed on Probe machine. See job documentation for more details') raise ValueError, 'Nmap is not installed on Probe machine' logger.debug('end executing nmap.exe')
def dump(self, host): permissions = {} root = ntpath.normpath("\\{}".format(self.__permdir)) for share in self.__smbconnection.listShares(): share_name = share['shi1_netname'][:-1] permissions[share_name] = [] try: if self.__smbconnection.listPath(share_name, '*'): permissions[share_name].append('READ') except SessionError: pass try: if self.__smbconnection.createDirectory(share_name, root): self.__smbconnection.deleteDirectory(share_name, root) permissions[share_name].append('WRITE') except SessionError: pass self.__logger.success('Enumerating shares') self.__logger.results('{:<10} {}'.format('SHARE', 'Permissions')) self.__logger.results('{:<10} {}'.format('-----', '-----------')) for share, perm in permissions.iteritems(): if not perm: self.__logger.results(u'{:<10} {}'.format(share, 'NO ACCESS')) else: self.__logger.results(u'{:<10} {}'.format(share, ', '.join(perm)))
def _parse_win32(cls, volume_config, normalize): # relative paths in windows expand to include the drive, eg C:\ # so we join the first 2 parts back together to count as one mode = 'rw' def separate_next_section(volume_config): drive, tail = splitdrive(volume_config) parts = tail.split(':', 1) if drive: parts[0] = drive + parts[0] return parts parts = separate_next_section(volume_config) if len(parts) == 1: internal = parts[0] external = None else: external = parts[0] parts = separate_next_section(parts[1]) external = ntpath.normpath(external) internal = parts[0] if len(parts) > 1: if ':' in parts[1]: raise ConfigurationError( "Volume %s has incorrect format, should be " "external:internal[:mode]" % volume_config ) mode = parts[1] if normalize: external = normalize_path_for_engine(external) if external else None result = cls(external, internal, mode) result.win32 = True return result
def download_file(self, host, path, verbose=True): path = path.replace('/','\\') path = ntpath.normpath(path) filename = path.split('\\')[-1] share = path.split('\\')[0] path = path.replace(share, '') try: out = open(ntpath.basename('%s/%s' % (os.getcwd(), '%s-%s%s' % (host, share, path.replace('\\','_')))),'wb') dlFile = self.smbconn[host].listPath(share, path) if verbose: msg = '[+] Starting download: %s (%s bytes)' % ('%s%s' % (share, path), dlFile[0].get_filesize()) if self.pattern: msg = '\t' + msg print msg self.smbconn[host].getFile(share, path, out.write) if verbose: msg = '[+] File output to: %s/%s' % (os.getcwd(), ntpath.basename('%s/%s' % (os.getcwd(), '%s-%s%s' % (host, share, path.replace('\\','_'))))) if self.pattern: msg = '\t'+msg print msg except SessionError as e: if 'STATUS_ACCESS_DENIED' in str(e): print '[!] Error retrieving file, access denied' elif 'STATUS_INVALID_PARAMETER' in str(e): print '[!] Error retrieving file, invalid path' elif 'STATUS_SHARING_VIOLATION' in str(e): print '[!] Error retrieving file, sharing violation' except Exception as e: print '[!] Error retrieving file, unkown error' os.remove(filename) out.close() return '%s/%s' % (os.getcwd(), ntpath.basename('%s/%s' % (os.getcwd(), '%s-%s%s' % (host, share, path.replace('\\','_')))))
def test_normpath(self): tester("ntpath.normpath('A//////././//.//B')", r'A\B') tester("ntpath.normpath('A/./B')", r'A\B') tester("ntpath.normpath('A/foo/../B')", r'A\B') tester("ntpath.normpath('C:A//B')", r'C:A\B') tester("ntpath.normpath('D:A/./B')", r'D:A\B') tester("ntpath.normpath('e:A/foo/../B')", r'e:A\B') tester("ntpath.normpath('C:///A//B')", r'C:\A\B') tester("ntpath.normpath('D:///A/./B')", r'D:\A\B') tester("ntpath.normpath('e:///A/foo/../B')", r'e:\A\B') tester("ntpath.normpath('..')", r'..') tester("ntpath.normpath('.')", r'.') tester("ntpath.normpath('')", r'.') tester("ntpath.normpath('/')", '\\') tester("ntpath.normpath('c:/')", 'c:\\') tester("ntpath.normpath('/../.././..')", '\\') tester("ntpath.normpath('c:/../../..')", 'c:\\') tester("ntpath.normpath('../.././..')", r'..\..\..') tester("ntpath.normpath('K:../.././..')", r'K:..\..\..') tester("ntpath.normpath('C:////a/b')", r'C:\a\b') tester("ntpath.normpath('//machine/share//a/b')", r'\\machine\share\a\b') # Issue 5827: Make sure normpath preserves unicode for path in (u'', u'.', u'/', u'\\', u'///foo/.//bar//'): self.assertTrue(isinstance(ntpath.normpath(path), unicode), 'normpath() returned str instead of unicode')
def delete_file(self, host, path, verbose=True): path = path.replace('/','\\') path = ntpath.normpath(path) filename = path.split('\\')[-1] share = path.split('\\')[0] path = path.replace(share, '') path = path.replace(filename, '') try: self.smbconn[host].deleteFile(share, path + filename) if verbose: success('[+] File successfully deleted: %s%s%s' % (share, path, filename)) except SessionError as e: if 'STATUS_ACCESS_DENIED' in str(e): if verbose: warning('[!] Error deleting file, access denied') elif 'STATUS_INVALID_PARAMETER' in str(e): if verbose: warning('[!] Error deleting file, invalid path') elif 'STATUS_SHARING_VIOLATION' in str(e): if verbose: warning('[!] Error retrieving file, sharing violation') else: warning('[!] Error deleting file %s%s%s, unknown error' % (share, path, filename)) warning('[!]', e) except Exception as e: warning('[!] Error deleting file %s%s%s, unknown error' % (share, path, filename)) warning('[!]', e)
def testCase_009(self): """local: os.path.normpath() == filesysobjects.paths.normpathx(tpf='local') """ if RTE is RTE_WIN32: import ntpath x0 = ntpath.normpath('\/') else: import posixpath x0 = posixpath.normpath('\/') self.assertEqual(x0, os.path.normpath('\/')) x1 = normpathx('\/',tpf='local', strip=False) if RTE is RTE_WIN32: if V3K: self.assertEqual(x0, '\\') else: try: self.assertEqual(x0, '\\') except AssertionError as e: sys.stderr.write( str(e) + "\nERROR:Python: Bug of Python2.7 for win32: '\\\\' instead of '\\'" + '\n' ) else: self.assertEqual(x0, '\\') self.assertEqual(x0, x1)
def get_file_location(self, pathformat=None): """Returns a tuple with the location of the file in the form ``(server, location)``. If the netloc is empty in the URL or points to localhost, it's represented as ``None``. The `pathformat` by default is autodetection but needs to be set when working with URLs of a specific system. The supported values are ``'windows'`` when working with Windows or DOS paths and ``'posix'`` when working with posix paths. If the URL does not point to a local file, the server and location are both represented as ``None``. :param pathformat: The expected format of the path component. Currently ``'windows'`` and ``'posix'`` are supported. Defaults to ``None`` which is autodetect. """ if self.scheme != "file": return None, None path = url_unquote(self.path) host = self.netloc or None if pathformat is None: if os.name == "nt": pathformat = "windows" else: pathformat = "posix" if pathformat == "windows": if path[:1] == "/" and path[1:2].isalpha() and path[2:3] in "|:": path = path[1:2] + ":" + path[3:] windows_share = path[:3] in ("\\" * 3, "/" * 3) import ntpath path = ntpath.normpath(path) # Windows shared drives are represented as ``\\host\\directory``. # That results in a URL like ``file://///host/directory``, and a # path like ``///host/directory``. We need to special-case this # because the path contains the hostname. if windows_share and host is None: parts = path.lstrip("\\").split("\\", 1) if len(parts) == 2: host, path = parts else: host = parts[0] path = "" elif pathformat == "posix": import posixpath path = posixpath.normpath(path) else: raise TypeError("Invalid path format %s" % repr(pathformat)) if host in ("127.0.0.1", "::1", "localhost"): host = None return host, path
def get_file_location(self, pathformat=None): """Returns a tuple with the location of the file in the form ``(server, location)``. If the netloc is empty in the URL or points to localhost, it's represented as ``None``. The `pathformat` by default is autodetection but needs to be set when working with URLs of a specific system. The supported values are ``'windows'`` when working with Windows or DOS paths and ``'posix'`` when working with posix paths. If the URL does not point to to a local file, the server and location are both represented as ``None``. :param pathformat: The expected format of the path component. Currently ``'windows'`` and ``'posix'`` are supported. Defaults to ``None`` which is autodetect. """ if self.scheme != 'file': return None, None path = url_unquote(self.path) host = self.netloc or None if pathformat is None: if os.name == 'nt': pathformat = 'windows' else: pathformat = 'posix' if pathformat == 'windows': if path[:1] == '/' and path[1:2].isalpha() and path[2:3] in '|:': path = path[1:2] + ':' + path[3:] windows_share = path[:3] in ('\\' * 3, '/' * 3) import ntpath path = ntpath.normpath(path) # Windows shared drives are represented as ``\\host\\directory``. # That results in a URL like ``file://///host/directory``, and a # path like ``///host/directory``. We need to special-case this # because the path contains the hostname. if windows_share and host is None: parts = path.lstrip('\\').split('\\', 1) if len(parts) == 2: host, path = parts else: host = parts[0] path = '' elif pathformat == 'posix': import posixpath path = posixpath.normpath(path) else: raise TypeError('Invalid path format %s' % repr(pathformat)) if host in ('127.0.0.1', '::1', 'localhost'): host = None return host, path
def join_path(self, *args): # use normpath() to remove doubled slashed and convert forward to backslashes parts = [ntpath.normpath(self._unquote(arg)) for arg in args] # Becuase ntpath.join treats any component that begins with a backslash as an absolute path, # we have to strip slashes from at least the beginning, otherwise join will ignore all previous # path components except for the drive. return ntpath.join(parts[0], *[part.strip('\\') for part in parts[1:]])
def testCase012(self): _in = 'd:/a' if RTE & RTE_WIN32: resX = ntpath.normpath('d:\\a') else: resX = posixpath.normpath('d:/a') res = filesysobjects.paths.normpathx(_in, spf='win', tpf='local') self.assertEqual(res, resX)
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
def adjustDcfFileRef(self, dcf, basedir): for elem in dcf['fileRef']: 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'\\', '/')
def __init__(self, fileAbsPath = sys.argv[0]): #setting command line elements self.binaryConverter = "./HandBrakeCli.exe" self.profile = "preset.json" fileAbsPath = ntpath.normpath(fileAbsPath) self.path, self.inputFile = ntpath.split(fileAbsPath) self.outputFile = "out." + self.inputFile self.setCmd()
def build_modo_batch(commands=[], headless=""): import ntpath searchpath = [TEMPLATES] engine = Engine(loader=FileLoader(searchpath), extensions=[CoreExtension()]) template = engine.get_template('modo_batch.bat') win_commands = [] for command in commands: win_commands.append(ntpath.normpath(format_filename(command, 'win32'))) headless = ntpath.normpath( r"C:\Program Files\Luxology\modo\11.0v1\modo_cl.exe") return template.render({ 'modo_cl': ntpath.normpath(headless), 'commands': win_commands })
def output_shares(self, host, lsshare, lspath, verbose=True): shareList = [lsshare] if lsshare else self.get_shares(host) for share in shareList: error = 0 pathList = {} canWrite = False try: root = string.replace('/%s' % (PERM_DIR),'/','\\') root = ntpath.normpath(root) self.create_dir(host, share, root) print '\t%s\tREAD, WRITE' % (share.ljust(50)) canWrite = True try: self.remove_dir(host, share, root) except: print '\t[!] Unable to remove test directory at \\\\%s\\%s%s, plreae remove manually' % (host, share, root) except Exception as e: #print e exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] #print(exc_type, fname, exc_tb.tb_lineno) sys.stdout.flush() canWrite = False if canWrite == False: readable = self.list_path(host, share, '', self.pattern, False) if readable: print '\t%s\tREAD ONLY' % (share.ljust(50)) else: error += 1 if error == 0 and (len(set(sys.argv).intersection(['-r','-R'])) == 1): path = '/' if self.list_files and not self.recursive: if lsshare and lspath: if self.pattern: print '\t[+] Starting search for files matching \'%s\' on share %s.' % (self.pattern, lsshare) dirList = self.list_path(host, lsshare, lspath, self.pattern, verbose) sys.exit() else: if self.pattern: print '\t[+] Starting search for files matching \'%s\' on share %s.' % (self.pattern, share) dirList = self.list_path(host, share, path, self.pattern, verbose) if self.recursive: if lsshare and lspath: if self.pattern: print '\t[+] Starting search for files matching \'%s\' on share %s.' % (self.pattern, lsshare) dirList = self.list_path_recursive(host, lsshare, lspath, '*', pathList, pattern, verbose) sys.exit() else: if self.pattern: print '\t[+] Starting search for files matching \'%s\' on share %s.' % (self.pattern, share) dirList = self.list_path_recursive(host, share, path, '*', pathList, pattern, verbose) if error > 0: print '\t%s\tNO ACCESS' % (share.ljust(50)) error = 0
def download_file(self, host, path, verbose=True): path = path.replace('/', '\\') path = ntpath.normpath(path) filename = path.split('\\')[-1] share = path.split('\\')[0] path = path.replace(share, '') try: out = open( ntpath.basename( '%s/%s' % (os.getcwd(), '%s-%s%s' % (host, share.replace('$', ''), path.replace('\\', '_')))), 'wb') dlFile = self.smbconn[host].listPath(share, path) if verbose: msg = '[+] Starting download: %s (%s bytes)' % ( '%s%s' % (share, path), dlFile[0].get_filesize()) if self.pattern: msg = '\t' + msg print(msg) self.smbconn[host].getFile(share, path, out.write) if verbose: msg = '[+] File output to: %s/%s' % ( os.getcwd(), ntpath.basename('%s/%s' % (os.getcwd(), '%s-%s%s' % (host, share.replace('$', ''), path.replace('\\', '_'))))) if self.pattern: msg = '\t' + msg print(msg) except SessionError as e: if 'STATUS_ACCESS_DENIED' in str(e): print('[!] Error retrieving file, access denied') elif 'STATUS_INVALID_PARAMETER' in str(e): print('[!] Error retrieving file, invalid path') elif 'STATUS_SHARING_VIOLATION' in str(e): if not verbose: indent = '\t' else: indent = '' print( f'{indent}[!] Error retrieving file {filename}, sharing violation' ) out.close() os.remove( ntpath.basename('%s/%s' % (os.getcwd(), '%s-%s%s' % (host, share.replace('$', ''), path.replace('\\', '_'))))) except Exception as e: print('[!] Error retrieving file, unkown error') os.remove(filename) out.close() return '%s/%s' % ( os.getcwd(), ntpath.basename( '%s/%s' % (os.getcwd(), '%s-%s%s' % (host, share.replace('$', ''), path.replace('\\', '_')))))