You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中使用域用户账号访问Windows文件共享

针对Linux GitLab Runner访问SMB共享的最优实现方案

你当前直接用open()访问UNC路径的写法仅支持Windows系统,Linux原生不支持该方式访问SMB文件共享,结合你使用服务账号、CI场景的需求,推荐以下两种可行方案:

方案1:Python代码层直接调用SMB协议(优先推荐)

该方案无需修改Runner系统配置、无需root权限,所有逻辑在代码内完成,适配临时CI任务场景:

  • 首先安装SMB协议依赖库:pip install smbprotocol
  • 替换原有访问逻辑,直接在代码中传入服务账号凭证,示例代码如下:
import os
import uuid
from smbprotocol.connection import Connection
from smbprotocol.session import Session
from smbprotocol.file import File, OpenMode

# 从环境变量读取凭证,不要硬编码
smb_server = "testserver"
share_name = "testshare" # 需替换为实际共享目录名
file_path = "testfile.txt"
username = os.getenv("SMB_USER")
password = os.getenv("SMB_PASS")
domain = os.getenv("SMB_DOMAIN", "") # 域账号填AD域名,本地账号留空

try:
    # 建立SMB连接
    conn = Connection(uuid.uuid4(), smb_server)
    conn.connect()
    session = Session(conn, username=username, password=password, domain=domain)
    session.connect()
    
    # 打开文件读取
    with File(session, share_name, file_path, desired_access=OpenMode.GENERIC_READ) as f:
        content = f.read().decode("utf-8")
        lines = content.splitlines()
        print(lines)
finally:
    # 断开连接
    if 'conn' in locals():
        conn.disconnect()
  • 提前在GitLab项目的CI/CD设置中新增加密变量SMB_USER、SMB_PASS、SMB_DOMAIN存储服务账号信息,避免凭证泄露。

方案2:CI任务前置挂载SMB共享到本地

如果你的多个CI步骤都需要访问共享文件,可在任务执行前完成系统级挂载:

  • 要求Runner配置了sudo权限允许挂载cifs文件系统
  • 在.gitlab-ci.yml的before_script中添加挂载逻辑:
before_script:
  - sudo apt update && sudo apt install -y cifs-utils
  - sudo mkdir -p /mnt/smb_share
  - sudo mount -t cifs //testserver/testshare /mnt/smb_share -o username=$SMB_USER,password=$SMB_PASS,domain=$SMB_DOMAIN,ro
  • 你的原有代码仅需要修改路径为本地挂载路径即可:
database_path = "/mnt/smb_share/testfile.txt"
try:
    with open(database_path, "r") as testfile:
        lines = testfile.readlines()
        print(lines)
except FileNotFoundError:
    print("Couldn't access the test file.")
  • 任务执行结束后系统会自动卸载挂载目录,无需手动清理。

注意事项

  • 禁止将服务账号凭证硬编码到代码仓库,所有敏感信息必须通过GitLab CI加密变量传递
  • 若SMB服务器使用的是SMB 1.0协议,需在对应配置中额外添加协议版本参数适配

内容的提问来源于stack exchange,提问作者user14909990

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 05:36:08