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

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


Building off of @Anon's suggestion:

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

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


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


I don't have a server to test with here at home, but maybe you could simply use the standard library's subprocess module to execute the appropriate NET USE command?

Looking at NET HELP USE from a windows command prompt, looks like you should be able to enter both the password and user id in the net use command to map the drive.

A quick test in the interpreter of a bare net use command w/o the mapping stuff:

>>> import subprocess>>> subprocess.check_call(['net', 'use'])New connections will be remembered.There are no entries in the list.0>>>