Python - 如何使用用户名和密码打开 Windows 共享
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5593198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - How to open Windows share using user name and password
提问by Rafal
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?
我想从 Python 脚本访问 Windows 共享(例如 \backupserver\backups)。共享受用户名和密码保护。如何使用用户名和密码打开此共享,例如列出其内容?
采纳答案by Andreas Jung
Why don't you mount the related share using the
为什么不使用挂载相关共享
NET USE
command?
命令?
Calling NET USE
from through the subprocess module is straight forward.
NET USE
通过子流程模块调用是直接的。
回答by Rafal
Complete example for "NET USE":
“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.")
回答by gimel
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.
使用pywin32
(Python for Windows Extensions),访问win32wnet
模块中的 Windows 网络方法。该win32wnet.WNetAddConnection2()
方法允许您指定用户名和密码。
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.
连接激活后,使用常规目录和文件方法访问共享。
回答by Baczek
A nice library that wraps 'net use' command:
一个很好的库,它包装了“net use”命令: