Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Accessing Windows mapped network drive with known URL, but unknown drive letter

Tags:

python

I am trying to write a Python script that can move and copy files on a remote Linux server. However, I can't assume that everyone running the script (on Windows) will have mapped this server to the same letter. Rather than prompting users for the correct letter, I want to simply access the server by its network URL, the one that the drive letter is mapped to. So, for instance, if I have mapped the server's URL

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

To be drive S:\, I want to access, say, the file S:\var\SomeFile.txt in a drive-letter agnostic manner. I have 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 this, an IOError saying there is no such file or directory. If I try using the server's IP address instead (not the real address, but similar):

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

I get, after a long pause, an IO Error: "invalid mode ('w') or filename". Why are these notations not working, and how can I access this server (ideally as if it were a local drive) by its URL?

like image 888
dpitch40 Avatar asked Oct 04 '12 14:10

dpitch40


2 Answers

Easy solution is to use forward slashes to specify the Universal Name Convention (UNC):

//HOST/share/path/to/file

Found this solution in another thread and felt it would be relevant here. See original thread below:

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

like image 86
UnNatural Avatar answered Nov 13 '22 09:11

UnNatural


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

From here:

import win32api

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

Then you could use os.path.exists() on every drive:\var\SomeFile.txt until you find the right one.

like image 5
Junuxx Avatar answered Nov 13 '22 07:11

Junuxx