使用 Python 中的域用户帐户访问 Windows 文件共享

Accessing Windows Fileshares with a domain user account in Python

我正在开发一种工具来自动生成一些文档并将它们存储在文件共享中。我有一个具有所需访问权限的服务帐户,我正在尝试了解如何最好地指定我想在访问文件共享时使用该帐户。

这是我尝试访问我的测试文件的相关测试代码:

database_path = "\\testserver\testfile.txt"
try:
    with open(database_path, "r") as testfile:
        lines = testfile.readlines()
        print(lines)
        testfile.close()
except FileNotFoundError:
    print("Couldn't access the test file.")

我 运行 通过 linux 运行程序通过 gitlab 进行此操作,因此搭载现有域用户帐户不是理想的解决方案。

有什么想法吗?

您可以简单地使用 cifs-utils 和 mount

将文件共享挂载到 Linux 文件系统
sudo mount -t cifs -o username=<win_share_user>,password=<password> //<WIN_SHARE_HOST>/<share_name> /mnt/my_share

然后在Python中打开你想要的文件,例如open('/mnt/my_share/path/to/file')

您需要在 linux 盒子上安装 cifs-utils:

apt install cifs-utils 对于 ubuntu/debian 或
yum install cifs-utils 软呢帽或
apk add cifs-utils 高山

或者,您可以使用任何支持 samba(Windows 使用的底层标准)文件共享协议的 Python 包,例如 fs.smbfs.

import fs
smb_fs = fs.open_fs('smb://username:password@SAMBAHOSTNAME:port/share')