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

使用服务账户通过Python访问Windows Server 2012 R2文件

用Python通过服务账户访问Windows Server 2012 R2网络共享文件

没问题,我来帮你搞定这个需求!下面给你两个实用的Python方案,都是通过网络共享方式访问文件,完全不需要RDP,而且只用你的服务账户凭据就行。

方案一:用pywin32映射网络驱动器

这个方案是先把远程共享映射成本地的一个虚拟驱动器,然后就像操作本地文件一样访问了,上手门槛低,操作逻辑和本地文件完全一致。

步骤1:安装依赖库

打开命令行,运行:

pip install pywin32

步骤2:Python代码示例

import win32net
import win32netcon
import os

# 替换成你的实际配置信息
server_name = "\\\\your-server-ip-or-hostname"
share_name = "your-target-share-folder"
username = "domain\\service-account"  # 域账户用这个格式,本地账户直接写账户名即可
password = "your-service-account-password"
drive_letter = "Z:"  # 选一个没被占用的盘符

# 映射网络驱动器并操作文件
try:
    # 构造连接参数
    net_resource = {
        'remote': f"{server_name}\\{share_name}",
        'local': drive_letter,
        'provider': win32netcon.RESOURCETYPE_DISK
    }
    win32net.NetUseAdd(None, 2, net_resource, username, password)
    print(f"成功映射驱动器 {drive_letter} 到 {server_name}\\{share_name}")

    # 示例1:列出共享文件夹内的所有文件/文件夹
    print("\n共享文件夹内容:")
    for item in os.listdir(drive_letter):
        print(f"- {item}")

    # 示例2:读取某个文件的内容
    target_file = f"{drive_letter}\\sample.txt"
    if os.path.exists(target_file):
        with open(target_file, 'r', encoding='utf-8') as f:
            content = f.read()
            print(f"\n文件内容:\n{content}")

finally:
    # 用完后可选断开驱动器(如果不需要长期保留映射的话)
    try:
        win32net.NetUseDel(None, drive_letter, win32netcon.USE_FORCE)
        print(f"\n已断开驱动器 {drive_letter}")
    except Exception as e:
        print(f"\n断开驱动器时出错: {str(e)}")

关键注意点

  • 一定要确认你的服务账户同时拥有共享权限和NTFS权限的读取权限,两个权限缺一个都不行。
  • 如果服务器在域环境中,用户名必须写成域名\\账户名的格式;本地账户直接写账户名即可。

方案二:用smbprotocol直接访问(无需映射驱动器)

这个方案更轻量,不需要占用本地盘符,直接通过SMB协议和远程服务器交互,适合不想修改本地驱动器配置的场景。

步骤1:安装依赖库

pip install smbprotocol

步骤2:Python代码示例

from smbprotocol.connection import Connection
from smbprotocol.session import Session
from smbprotocol.tree import TreeConnect

# 替换成你的实际配置信息
server_ip = "your-server-ip"
share_name = "your-target-share-folder"
username = "domain\\service-account"
password = "your-service-account-password"

# 建立SMB连接并操作文件
with Connection(server_ip, 445) as conn:
    conn.connect()
    with Session(conn, username, password) as session:
        with TreeConnect(session, f"\\\\{server_ip}\\{share_name}") as tree:
            # 示例1:列出共享文件夹内的内容
            print("共享文件夹内容:")
            for file_info in tree.list_directory("\\"):
                print(f"- {file_info['file_name']}")

            # 示例2:读取目标文件内容
            target_file_path = "\\sample.txt"
            with tree.open_file(target_file_path, "r") as file:
                content_bytes = file.read()
                print(f"\n文件内容:\n{content_bytes.decode('utf-8')}")

关键注意点

  • Windows Server 2012 R2默认开启SMB 2.0+,这个库完美支持,兼容性没问题。
  • 如果连接失败,先检查服务器防火墙是否允许445端口(SMB协议默认端口)的入站请求。

通用提醒

不管用哪个方案,都要确保:

  • 服务账户的凭据完全正确,且确实拥有目标文件的读取权限。
  • 你的运行环境和目标服务器处于同一网络(比如局域网、VPN连接),能正常访问服务器IP/主机名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:13:03