def uncpath(filepath): ''' Convert file path to UNC. @type filepath: C{str} @param filepath: Path to file @rtype: C{str} @return: UNC filepath (if on Windows) ''' #if sys.platform[0:3].lower()=='win': if iswin: import win32wnet if hasattr(filepath, '__iter__'): #Is iterable uncpath = [] for path in filepath: try: uncpath.append( normcase(win32wnet.WNetGetUniversalName(path))) except: uncpath.append(normcase(path)) #Local path #try: uncpath.append(win32wnet.WNetGetUniversalName(path)) #except: uncpath.append(path) #Local path else: try: uncpath = win32wnet.WNetGetUniversalName(filepath) except: uncpath = filepath #Local path else: uncpath = filepath return uncpath
def remote(pathname): """This converts the pathname of a file on a network file server from the local format to the format used on the MAR CCD compter. e.g. "//id14bxf/data" in Windows maps to "/net/id14bxf/data" on Unix""" if not pathname: return pathname # Try to expand a Windows drive letter to a UNC name. try: import win32wnet # Convert "J:/anfinrud_0811/Data" to "J:\anfinrud_0811\Data". pathname = pathname.replace("/", "\\") pathname = win32wnet.WNetGetUniversalName(pathname) except: pass # Convert separators from DOS style to UNIX style. pathname = pathname.replace("\\", "/") if pathname.find("//") == 0: # //server/share/directory/file parts = pathname.split("/") if len(parts) >= 4: server = parts[2] share = parts[3] path = "" for part in parts[4:]: path += part + "/" path = path.rstrip("/") pathname = "/net/" + server + "/" + share + "/" + path return pathname
def TestConnection(): if len(possible_shares) == 0: print "Couldn't find any potential shares to connect to" return localName = "Z:" # need better way! for share in possible_shares: print "Attempting connection of", localName, "to", share.lpRemoteName try: win32wnet.WNetAddConnection2(share.dwType, localName, share.lpRemoteName) except win32wnet.error, details: print "Couldn't connect: " + details[2] continue # Have a connection. try: fname = os.path.join(localName + "\\", os.listdir(localName + "\\")[0]) try: print "Universal name of '%s' is '%s'" % ( fname, win32wnet.WNetGetUniversalName(fname)) except win32wnet.error, details: print "Couldn't get universal name of '%s': %s" % (fname, details[2]) print "User name for this connection is", win32wnet.WNetGetUser( localName)
def main(argv): #------------------------------------------------------------------------------- """ usage: drives.py shows the available drives on the system and (free space/total space) """ args, opts = oss.gopt(argv[1:], [], [], main.__doc__) drives = w32.GetLogicalDrives() for i in range(26): if drives & (1 << i): dl = chr(i + ord('A')) rootpath = dl + ':\\' tp = w32.GetDriveType(rootpath) print(" %s:" % dl, S[tp], end='') try: f, t, d = w32.GetDiskFreeSpaceEx(rootpath) if tp == 4: print(" (%s/%s)" % (util.CvtGigMegKBytes(f), util.CvtGigMegKBytes(t)), end='') print(" [%s]" % wnet.WNetGetUniversalName(rootpath, 1)) else: print(" (%s/%s)" % (util.CvtGigMegKBytes(f), util.CvtGigMegKBytes(t))) except: print(" -- not ready") oss.exit(0)
def Windows_pathname(pathname): """Translate between UNIX-style to Windows-style pathnames, following Universal Naming Convention. E.g. "/net/id14bxf/data" to "\\id14bxf\data""" if pathname == "": return pathname if not pathname[1:2] == ":": # Resolve symbolic links. E.g. "/data" to "/net/id14bxf/data" from os.path import realpath pathname = realpath(pathname) # Mac OS X: mount point "/Volumes/share" does not reveal server name. if pathname.startswith("/Mirror/"): pathname = pathname.replace("/Mirror/", "//") if pathname.startswith("/Volumes/data"): pathname = pathname.replace("/Volumes/data", "/net/id14bxf/data") if pathname.startswith("/Volumes/C"): pathname = pathname.replace("/Volumes/C", "/net/femto/C") # Convert separators from UNIX style to Windows style. # E.g. "//id14bxf/data/anfinrud_1106" to "\\id14bxf\data\anfinrud_1106" pathname = pathname.replace("/", "\\") # Try to expand a Windows drive letter to a UNC name. # E.g. "J:/anfinrud_1106" to "//id14bxf/data/anfinrud_1106" try: import win32wnet pathname = win32wnet.WNetGetUniversalName(pathname) except: pass # Convert from UNIX to Windows style. # E.g. "/net/id14bxf/data/anfinrud_1106" to "//id14bxf/data/anfinrud_1106" if pathname.startswith("\\net\\"): parts = pathname.split("\\") if len(parts) >= 4: server = parts[2] share = parts[3] pathname = "\\\\" + pathname[5:] return pathname
def checkDriverMapping(): if (DEVMODE == '0'): subprocess.call("net use l: /delete /y", shell=True) subprocess.call("net use m: /delete /y", shell=True) os.system("net use l: {}".format(DRIVER_L)) os.system("net use m: {}".format(DRIVER_M)) logging.info("Driver L: Deleted and Mapped:" + DRIVER_L) logging.info("Driver M: Deleted and Mapped:" + DRIVER_M) else: try: logging.info("Driver L: Mapped:" + win32wnet.WNetGetUniversalName("L:", 1)) logging.info("Driver M: Mapped:" + win32wnet.WNetGetUniversalName("M:", 1)) except: logging.warn("Driver L: and M: Is Not Mapped") os.system("net use l: {}".format(DRIVER_L)) os.system("net use m: {}".format(DRIVER_M))
def cluster_path(path): try: import win32wnet drive, folder = os.path.splitdrive(abspath(path)) path = abspath(win32wnet.WNetGetUniversalName(drive, 1) + folder) except Exception: path = repl(path) path = path.replace("//jess.dtu.dk", "/home") path = path.replace("//mimer.risoe.dk/aiolos", "/mnt/aiolos") path = path.replace("//mimer.risoe.dk", "/mnt/mimer") return path
def write_values_to_file(data_dir): new_file = os.path.join(data_dir, "oracle_backup.txt") print new_file with open(new_file, "w") as f: if oracle_path.get(): try: oracle_path_unc = (win32wnet.WNetGetUniversalName( oracle_path.get(), 1)) except Exception as e: oracle_path_unc = oracle_path.get() f.write("oracle_path==%s\n" % (oracle_path_unc)) if your_path.get(): try: your_path_unc = (win32wnet.WNetGetUniversalName( your_path.get(), 1)) except Exception as e: your_path_unc = your_path.get() f.write("your_path==%s\n" % (your_path_unc)) folders = [] for res in folder_path_text.get("1.0", END).split("\n"): if res: try: folders.append( (win32wnet.WNetGetUniversalName(folder_path.get(), 1))) except Exception as e: folders.append(res) if folders: f.write("folder_path_text==%s\n" % str(folders)) if backup_time_text.get(): f.write("backup_time_text==%s\n" % (backup_time_text.get())) if move_backup_time_text.get(): f.write("move_backup_time_text==%s\n" % (move_backup_time_text.get())) if users_to_backup.get(): f.write("users_to_backup_text==%s" % (users_to_backup.get().upper()))
def get_unc_path(path_) -> str: """Will try to convert path string to UNC path""" import win32wnet if path_[0].lower() == "c": return path_ else: try: out_path = win32wnet.WNetGetUniversalName(path_) return out_path except BaseException as e: logging.error(e) return path_
def CopyPath(filelist): # populate unorganized list. # This is the main logic where you add different path types. # rest of the function dont change unorglist = [] for file in filelist: unorglist.append(os.path.basename(file)) unorglist.append(file) unorglist.append(file.replace("\\", "\\\\")) unorglist.append(file.replace("\\", "/")) try: unorglist.append(win32wnet.WNetGetUniversalName(file, 1)) except: pass # create set of organized lists orglist = [] numpath = int(len(unorglist) / len(filelist)) for i in range(numpath): orglist.append([]) i = 0 for path in unorglist: if i >= numpath: i = 0 orglist[i].append(path) i += 1 # display menu i = 0 for item in orglist: print(i, item[0], end="") if len(item) > 1: print(", ", item[1], " ...") else: print("") i += 1 print("Enter your choice: ") idx = int(msvcrt.getch()) # copy to clipboard txt = "" if len(orglist[idx]) == 1: txt = orglist[idx][0] else: for item in orglist[idx]: txt = txt + item + "\n" clipboard.copy(txt)
def test_unc_path_multi_scanner_multi_accession(self): """This test attempts to test the UNC path capabilities. When the test file path is convertable to a UNC path, the tests from method 'test_multi_scanner_multi_accession' are run""" #TODO: the following code will raise an error (2250) when the path is a # on a local drive. I have tested that the following code works, # but the generic EXCEPTION is used in the TRY/EXCEPT statement # below. I'd like to replace this with somethin less general # Get the current file's absolute path try: d = win32wnet.WNetGetUniversalName(py.path.local(__file__).dirname) except Exception: pytest.skip('Unable to generate a UNC path with the current' + 'configuration') d = py.path.local(d) # Generate the directories as in the multi-scanner, multi-accession # number test nAcc = [random.randint(1, 10) for x in range(4)] accList, nImDirs = self._gen_dirs(d, nAcc=nAcc) # Instantiate a SectraListener object, walk the directory structure, # and validate that a single accession folder was found. Use the same # temporary directory to house the database to ensure that another # database is not loaded obj = pacstools.SectraListener(d.strpath, dirDataBase=d.strpath) obj.walk_dirs() # Before asserting the test results, clean-up the directories. Note # that the 'folders' path must be added because the parent # directory 'tests' must not be removed! d.join('folders').remove() # Perform three tests: (1) only one accession number has been found # and (2) that all accession numbers generated exist in the data # frame, (3) that the number of image directories matches the # number that were generated automatically assert (obj.data.loc[:, 'Accession'].size == len(accList)) for acc in accList: assert (obj.data.Accession.isin([acc]).any())
def TestConnection(): if len(possible_shares) == 0: print("Couldn't find any potential shares to connect to") return localName = findUnusedDriveLetter() + ':' for share in possible_shares: print("Attempting connection of", localName, "to", share.lpRemoteName) try: win32wnet.WNetAddConnection2(share.dwType, localName, share.lpRemoteName) except win32wnet.error as details: print("Couldn't connect: " + details.strerror) continue # Have a connection. try: fname = os.path.join(localName + "\\", os.listdir(localName + "\\")[0]) try: print("Universal name of '%s' is '%s'" % (fname, win32wnet.WNetGetUniversalName(fname))) except win32wnet.error as details: print("Couldn't get universal name of '%s': %s" % (fname, details.strerror)) print("User name for this connection is", win32wnet.WNetGetUser(localName)) finally: win32wnet.WNetCancelConnection2(localName, 0, 0) # and do it again, but this time by using the more modern # NETRESOURCE way. nr = win32wnet.NETRESOURCE() nr.dwType = share.dwType nr.lpLocalName = localName nr.lpRemoteName = share.lpRemoteName win32wnet.WNetAddConnection2(nr) win32wnet.WNetCancelConnection2(localName, 0, 0) # and one more time using WNetAddConnection3 win32wnet.WNetAddConnection3(0, nr) win32wnet.WNetCancelConnection2(localName, 0, 0) # Only do the first share that succeeds. break
def normpath(pathname): """Translate between UNIX-style to Windows-style pathnames, following Universal Naming Convention. E.g. "/net/mx340hs/data" to "//mx340hs/data""" if pathname == "": return pathname from os.path import exists pathname = str(pathname) # Try to expand a Windows drive letter to a UNC name. # E.g. "J:/anfinrud_1106" to "//mx340hs/data/anfinrud_1106" try: import win32wnet # http://sourceforge.net/projects/pywin32 pathname = win32wnet.WNetGetUniversalName(pathname) except: pass # Resolve symbolic links. E.g. "/data" to "/net/mx340hs/data" # E.g. "G:/anfinrud_1403/Logfiles" or "\\mx340hs\data\anfinrud_1403\Logfiles" import os if not pathname[1:2] == ":" and not "\\" in pathname \ and not pathname.startswith("//") and not os.name == "nt": from os.path import realpath pathname = realpath(pathname) # Convert separators from Window style to UNIX style. # E.g. "\\mx340hs\data\anfinrud_1106" to "//mx340hs/data/anfinrud_1106" pathname = pathname.replace("\\","/") # Mac OS X: mount point "/Volumes/share" does not reveal server name. if pathname.startswith("/Volumes/data"): pathname = pathname.replace("/Volumes/data","/net/mx340hs/data") if pathname.startswith("/Volumes/Femto"): pathname = pathname.replace("/Volumes/Femto","/net/femto/C") if pathname.startswith("/Volumes/C"): pathname = pathname.replace("/Volumes/C","/net/femto/C") # Convert from Windows to UNIX style. # E.g. "//mx340hs/data/anfinrud_1106" to "/net/mx340hs/data/anfinrud_1106" if pathname.startswith("//"): # //server/share/directory/file parts = pathname.split("/") if len(parts) >= 4: server = parts[2] ; share = parts[3] path = "/".join(parts[4:]) if not exists("//"+server+"/"+share): if exists("/net/"+server+"/"+share): pathname = "/net/"+server+"/"+share+"/"+path if exists("/net/"+server+"/home/"+share): pathname = "/net/"+server+"/home/"+share+"/"+path # Convert from UNIX to Windows style. # E.g. "/net/mx340hs/data/anfinrud_1106" to "//mx340hs/data/anfinrud_1106" from sys import platform if pathname.startswith("/net/") and platform in ("win32","darwin"): parts = pathname.split("/") if len(parts) >= 4: server = parts[2] ; share = parts[3] path = "/".join(parts[4:]) # E.g. /net/id14b4/home/useridb/NIH/Software if share == "home" and len(parts)>4: share = parts[4] path = "/".join(parts[5:]) pathname = "//"+server+"/"+share+"/"+path # E.g. "/home/useridb/NIH/Software" if not pathname.startswith("//") and pathname.startswith("/") and \ platform != "win32" and not pathname.startswith("/net/") and \ not pathname.startswith("/Volumes/"): from platform import node hostname = node() parts = pathname.strip("/").split("/") dir = "/".join(parts[0:2]) path = "/".join(parts) if exists("/net/"+hostname+"/"+dir): pathname = "/net/"+hostname+"/"+path return pathname