Python - How to open Windows share using user name and password
Solution 1
Why don't you mount the related share using the
NET USE
command?
Calling NET USE
from through the subprocess module is straight forward.
Solution 2
Complete example for "NET USE":
backup_storage_available = os.path.isdir(BACKUP_REPOSITORY_PATH)
if backup_storage_available:
logger.info("Backup storage already connected.")
else:
logger.info("Connecting to backup storage.")
mount_command = "net use /user:" + BACKUP_REPOSITORY_USER_NAME + " " + BACKUP_REPOSITORY_PATH + " " + BACKUP_REPOSITORY_USER_PASSWORD
os.system(mount_command)
backup_storage_available = os.path.isdir(BACKUP_REPOSITORY_PATH)
if backup_storage_available:
logger.fine("Connection success.")
else:
raise Exception("Failed to find storage directory.")
Solution 3
Using pywin32
(Python for Windows Extensions),
access the windows networking methods in the win32wnet
module.
The win32wnet.WNetAddConnection2()
method lets you specify username and password.
WNetAddConnection2(NetResource, Password, UserName, Flags)
Creates a connection to a network resource. The function can redirect a local device to the network resource.
After the connection is active, access the share using regular directory and file methods.
Related videos on Youtube
Rafal
Updated on June 04, 2022Comments
-
Rafal almost 2 years
I would like to access Windows share (ex. \backupserver\backups) from Python script. Share is protected by user name and password. How to open this share using user name and password and, for example list its content?
-
Andrey Grachev almost 9 yearsAn example of NetResource definition:
NetResource = win32wnet.NETRESOURCE()
NetResource.lpRemoteName = r'\\10.0.0.1\share'
-
Aleister Tanek Javas Mraz almost 5 yearsAnswer provides little insight into why and how the solution works.