0

I have established connection with a Windows Shared drive using Pywin32

import win32net
data = {
    'remote': r"\\server\shared",
    'local': '',
    'username': 'username',
    'password': 'password'
}

win32net.NetUseAdd(None, 2, data)

I need to list out all the files present in the shared folder, similar to os.walk(path).

What are the possible ways to do that?

CristiFati
  • 38,250
  • 9
  • 50
  • 87
Gary
  • 31
  • 1
  • 6

1 Answers1

0

Check [ME.TimGolden]: Python for Win32 Extensions Help
((officially) referenced by [GitHub]: mhammond/pywin32 - Python for Windows (pywin32) Extensions which is a Python wrapper ove WinAPIs).

win32net.NetUseAdd wraps [MS.Learn}: NetUseAdd function (lmuse.h).
[MS.Learn]: USE_INFO_2 structure (lmuse.h) (wrapt by [ME.TimGolden]: PyUSE_INFO_2 Object - that you used) states:

ui2_local

Type: LMSTR

A pointer to a string that contains the local device name (for example, drive E or LPT1) being redirected to the shared resource. The constant DEVLEN specifies the maximum number of characters in the string. This member can be NULL. For more information, see the following Remarks section.

All you have to do is:

  1. Provide a local name (that is not in use)

  2. Once the connection is successful, use that (just as any "regular" local drive)

code00.py:

#!/usr/bin/env python

import os
import sys

import win32net as wnet


def main(*argv):
    local_drive = "y:"
    data = {
        "remote": r"\\localhost\share_cfati",
        "local": local_drive,
        "username": "user",  # @TODO - cfati: Modified to hide sensitive data
        "password": "***",  # @TODO - cfati: Modified to hide sensitive data
    }

    try:
        res = wnet.NetUseAdd(None, 2, data)
        #print(res)
    except:
        print("Error adding connection:", sys.exc_info())
        return -1

    print("Items in the shared folder:\n{:}".format(os.listdir(local_drive)))


if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.\n")
    sys.exit(rc)

Output:

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q075267137]> sopr.bat
### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ###

[prompt]>
[prompt]> net share

Share name   Resource                        Remark

-------------------------------------------------------------------------------
ADMIN$       C:\WINDOWS                      Remote Admin
C$           C:\                             Default share
E$           E:\                             Default share
F$           F:\                             Default share
G$           G:\                             Default share
H$           H:\                             Default share
IPC$                                         Remote IPC
L$           L:\                             Default share
M$           M:\                             Default share
N$           N:\                             Default share
share_cfati  L:\Share\cfati
share_pub_ro L:\Share\pub_ro
share_pub_rw L:\Share\pub_rw
The command completed successfully.


[prompt]>
[prompt]> net use
New connections will not be remembered.

There are no entries in the list.


[prompt]>
[prompt]> "e:\Work\Dev\VEnvs\py_pc064_03.10_test0\Scripts\python.exe" ./code00.py
Python 3.10.9 (tags/v3.10.9:1dd9be6, Dec  6 2022, 20:01:21) [MSC v.1934 64 bit (AMD64)] 064bit on win32

Items in the shared folder:
['.DS_Store', 'a.py', 'b', 'c', 'code00.py', 'commander.dmg', 'copy_sdk-aars.sh', 'cstrike1.6.zip', 'dedus', 'doublecmd.xml', 'ifm', 'pula', 'py2713.tgz']

Done.


[prompt]>
[prompt]> net use
New connections will not be remembered.


Status       Local     Remote                    Network

-------------------------------------------------------------------------------
OK           Y:        \\localhost\share_cfati   Microsoft Windows Network
The command completed successfully.


[prompt]>
[prompt]> net use /delete y:
y: was deleted successfully.


[prompt]>
[prompt]> net use
New connections will not be remembered.

There are no entries in the list.

Notes:

  • This is the equivalent of Map network drive... feature from Win UI

  • Generally, when done with a resource it's best to release it. I removed the connection (net use /delete y:), but that can be also done from the code via win32net.NetUseDel*

  • File (folder) browsing itself is not part of this question (at least I don't consider it to be), as it's a different (stand alone) topic. Check [SO]: How do I list all files of a directory? (@CristiFati's answer) for a thorough analysis on how to do it

CristiFati
  • 38,250
  • 9
  • 50
  • 87