views:

1017

answers:

7

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

+1  A: 

I'd go with IronPython and this article : Mapping a Drive Letter Programmatically. Or you could use the Win32 API directly.

Geo
+1  A: 

Here are a couple links which show use of the win32net module that should provide the functionality you need.

http://docs.activestate.com/activepython/2.4/pywin32/html/win32/help/win32net.html http://www.blog.pythonlibrary.org/?p=20

Michael Mior
A: 

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
>>>
Anon
+1  A: 

Assuming that you import necessary libraries, This was a part of an RPC server where the client requested the server to map a drive locally...

#Small function to check the availability of network resource.
def isAvailable(path):
    winCMD = 'IF EXIST ' + path + ' echo YES'
    cmdOutPut = subprocess.Popen(winCMD, stdout=subprocess.PIPE, shell=True).communicate()
    return string.find(str(cmdOutPut), 'YES',)

#Small function to check if the mention location is a directory
def isDirectory(path):
    winCMD = 'dir ' + path + ' | FIND ".."'
    cmdOutPut = subprocess.Popen(winCMD, stdout=subprocess.PIPE, shell=True).communicate()
    return string.find(str(cmdOutPut), 'DIR',)

================Check the white spaces from here, these were a part of a function============

def mapNetworkDrive(self, drive, networkPath, user, password):

 #Check for drive availability
 if isAvailable(drive) > -1:
  #Drive letter is already in use
  return -1

 #Check for network resource availability
 if isAvailable(networkPath) == -1:
  print "Path not accessible: ", networkPath
  #Network path is not reachable
  return -1

 #Prepare 'NET USE' commands
 winCMD1 = 'NET USE ' + drive + ' ' + networkPath
 winCMD2 = winCMD1 + ' ' + password + ' /User' + user

 print "winCMD1 = ", winCMD1
 print "winCMD2 = ", winCMD2
 #Execute 'NET USE' command with authentication
 winCMD = winCMD2
 cmdOutPut = subprocess.Popen(winCMD, stdout=subprocess.PIPE, shell=True).communicate()
 print "Executed: ", winCMD
 if string.find(str(cmdOutPut), 'successfully',) == -1:
  print winCMD, " FAILED"
  winCMD = winCMD1
  #Execute 'NET USE' command without authentication, incase session already open
  cmdOutPut = subprocess.Popen(winCMD, stdout=subprocess.PIPE, shell=True).communicate()
  print "Executed: ", winCMD
  if string.find(str(cmdOutPut), 'successfully',) == -1:
   print winCMD, " FAILED"
   return -1
  #Mapped on second try
  return 1
 #Mapped with first try
 return 1

def unmapNetworkDrive(self, drive):

 #Check if the drive is in use
 if isAvailable(drive) == -1:
  #Drive is not in use
  return -1

 #Prepare 'NET USE' command
 winCMD = 'net use ' + drive + ' /DELETE'
 cmdOutPut = subprocess.Popen(winCMD, stdout=subprocess.PIPE, shell=True).communicate()
 if string.find(str(cmdOutPut), 'successfully',) == -1:
  #Could not UN-MAP, this might be a physical drive
  return -1
 #UN-MAP successful
 return 1
Varun
A: 

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
Varun
A: 

I am using Python 2.6.2 and trying to do the win32wnet method however I am find it hard to find a location to get the Win32wnet module.

I have python installed on x64 system.

any help in getting that module would be extremely helpful

Awilliams
A: 

@Awilliams, install pywin32 by Mark Hammond....

Varun
This should of been a comment.
Gary Willoughby