Python: accessing a networked Windows network drive with a known URL but an unknown drive letter

I am trying to write a Python script that can move and copy files on a remote Linux server. However, I cannot assume that everyone who runs the script (on Windows) will match this server with the same letter. Instead of offering users the correct email, I just want to access the server by its network URL, to which the drive letter is mapped. So for example, if I matched the server url

\\name-of-machine.site.company.com 

To be an S: \ drive, I want to access, say, the S: \ var \ SomeFile.txt file in agnostic form of the drive. I looked around, and the general recommendation seems to be to use UNC notation:

 f = open(r"\\name-of-machine.site.company.com\var\SomeFile.txt", "w") 

But if I try to do this, IOError says that there is no such file or directory. If I try to use the server IP address instead (not a real address, but similar):

 f = open(r"\\10.1.123.149\var\SomeFile.txt", "w") 

After a long pause, I get an IO error message: "Invalid mode (" w ") or file name." Why don't these notations work, and how can I access this server (ideally, like a local disk) using its URL?

+4
source share
4 answers

Not a very elegant solution, but can you just try all the drives?

From here :

 import win32api drives = win32api.GetLogicalDriveStrings() drives = drives.split('\000')[:-1] print drives 

Then you can use os.path.exists() on each drive: \ var \ SomeFile.txt until you find the correct one.

+5
source

A simple solution is to use a slash to indicate a universal convention (UNC):

 //HOST/share/path/to/file 

I found this solution in another thread and felt that it would be relevant here. See the source topic below:

Using Python, how can I access a shared folder on a Windows network?

+4
source

Try using a short name instead of a full name. In your example, it will be \\name-of-machine\var\SomeFile.txt .

Edit:

Well, now I feel like a mannequin - I hope you will feel with me!;)

The name of the machine is name-of-machine.site.company.com , and the name of the folder and file \var\SomeFile.txt is what is the name of the share? In other words, your path should look something like this:

 \\name-of-machine.site.company.com\share_name\var\SomeFile.txt 
0
source

If you can reserve a drive letter for this task, and you have privileges, you can run "net use ..." with python, and then use this fixed letter to read / write files.

http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/net_use.mspx?mfr=true

0
source

Source: https://habr.com/ru/post/1437833/


All Articles