Search code examples
pythonwindowswmiremote-access

Login to a remote Windows machine to access shared files with Python


I have a remote machine with shared files. This can easily be accessed via Windows Explorer, you just navigate to the path, provide the domain username and password and can view the files. Now I was trying to automate a task with a Python script and access the same folder programmatically. Looks like Python's os module doesn't provide API for doing this. I can still get to the folder using:

os.listdir(myPath)

but it shows a windows authentication error. WindowsError: [Error 1326] Logon failure: unknown user name or bad password.

Are there any alternative packages in PyPI or some other built in way to authenticate on a remote machine? WMI won't do because I can't install WMI on the remote machine.


Solution

  • You can use netuse module. Plese check that site

    There are two options:

    1) Connect by virtual connection

    2) Mount remote computer drive in local system

    1)

    import win32api
    import win32net
    ip = '192.168.1.18'
    username = 'ram'
    password = 'ram@123'
    
    use_dict={}
    use_dict['remote']=unicode('\\\\192.168.1.18\C$')
    use_dict['password']=unicode(password)
    use_dict['username']=unicode(username)
    win32net.NetUseAdd(None, 2, use_dict)
    

    2)

    import win32api
    import win32net
    import win32netcon,win32wnet
     
    username=’user’
    password=’psw’
     
    try:
        win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, 'Z:','\\\\192.168.1.18\\D$', None, username,password, 0)
        print “connection established successfully”
    except:
        print  “connection not established”