faqts : Computers : Programming : Languages : Python : Platforms : Windows

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 6 people (50%) answered Yes
Recently 2 of 5 people (40%) answered Yes

Entry

How can I map a drive using pythonwin, and see if it was successful or not?

Apr 3rd, 2007 14:44
Rob Hausler, unknown unknown, Fred Gansevles, Roger Upole


This code written using the 'dynwin' package.

# wnet.py -- wnet module

from dynwin import winwin, winclass, msgloop, windll
from dynwin.structob import struct_object
from dynwin.oracle import Oracle

mpr = windll.module ('mpr')

RESOURCETYPE_DISK       = 0x00000001

class NETRESOURCE (struct_object):
        oracle = Oracle (
                'NETRESOURCE',
                'Lllllllll',
                ('dwScope',
                 'dwType',
                 'dwDisplayType',
                 'dwUsage',
                 'lpLocalName',
                 'lpRemoteName',
                 'lpComment',
                 'lpProvider')
                )

def use(drive, host, user, passwd):
    nr = NETRESOURCE()
    nr.dwType = RESOURCETYPE_DISK
    lpLocalName = windll.cstring(drive)
    lpRemoteName = windll.cstring(r'\\%s\%s' % (host, user))
    lpProvider = windll.cstring('Microsoft Windows Network')
    nr.lpLocalName = lpLocalName.address()
    nr.lpRemoteName = lpRemoteName.address()
    nr.lpProvider = lpProvider.address()
    return mpr.WNetAddConnection2(nr,
                windll.cstring(passwd), windll.cstring(user), 0)

def unuse(drive):
    return mpr.WNetCancelConnection2(windll.cstring(drive), 1, 1)

------------

You should be able to use the COM interface for Windows Scripting host.
import win32com.client
wnt=win32com.client.Dispatch('Wscript.Network')
wnt.MapNetworkDrive('z:','//someserver/someshare')
To test it, just try to access the drive:
os.listdir('z:') or something similar.

-----------------

Similar, but displays error if doesn't work.

import win32com.client
wshnetwork = win32com.client.Dispatch('Wscript.Network')
try:
    wshnetwork.MapNetworkDrive('z:', \\\\server\\someshare')
exception Exception, err:
    print err