Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to map windows drives using Python?

What is the best way to map a network share to a windows drive using Python? This share also requires a username and password.

like image 420
Gary Willoughby Avatar asked Aug 13 '09 11:08

Gary Willoughby


People also ask

What is GPO drive mapping?

The Drive Maps policy in Group Policy preferences allows an administrator to manage drive letter mappings to network shares. Steps involved: Open Group Policy Management. Right-click the domain or the required subfolder to create a new GPO, or select an already existing one.


2 Answers

Building off of @Anon's suggestion:

# Drive letter: M # Shared drive path: \\shared\folder # Username: user123 # Password: password import subprocess  # Disconnect anything on M subprocess.call(r'net use m: /del', shell=True)  # Connect to shared drive, use drive letter M subprocess.call(r'net use m: \\shared\folder /user:user123 password', shell=True) 

I prefer this simple approach, especially if all the information is static.

like image 102
aqua Avatar answered Sep 25 '22 12:09

aqua


Okay, Here's another method...

This one was after going through win32wnet. Let me know what you think...

def mapDrive(drive, networkPath, user, password, force=0):     print networkPath     if (os.path.exists(drive)):         print drive, " Drive in use, trying to unmap..."         if force:             try:                 win32wnet.WNetCancelConnection2(drive, 1, 1)                 print drive, "successfully unmapped..."             except:                 print drive, "Unmap failed, This might not be a network drive..."                 return -1         else:             print "Non-forcing call. Will not unmap..."             return -1     else:         print drive, " drive is free..."     if (os.path.exists(networkPath)):         print networkPath, " is found..."         print "Trying to map ", networkPath, " on to ", drive, " ....."         try:             win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, drive, networkPath, None, user, password)         except:             print "Unexpected error..."             return -1         print "Mapping successful"         return 1     else:         print "Network path unreachable..."         return -1 

And to unmap, just use....

def unmapDrive(drive, force=0):     #Check if the drive is in use     if (os.path.exists(drive)):         print "drive in use, trying to unmap..."         if force == 0:             print "Executing un-forced call..."         try:             win32wnet.WNetCancelConnection2(drive, 1, force)             print drive, "successfully unmapped..."             return 1         except:             print "Unmap failed, try again..."             return -1     else:         print drive, " Drive is already free..."         return -1 
like image 43
Varun Avatar answered Sep 25 '22 12:09

Varun