使用smbprotocol复制服务器文件失败:STATUS_FILE_CLOSED错误排查
问题原因
你遇到的 STATUS_FILE_CLOSED 错误是因为目标文件没有被正确打开。在使用 smbprotocol 的 Open 对象时,必须调用 create() 方法向SMB服务器发送打开(或创建)文件的请求,否则文件句柄未被初始化,后续的写入操作会被视为对已关闭文件的操作。
修正后的代码
import uuid from smbprotocol.connection import Connection from smbprotocol.open import ( CreateDisposition, CreateOptions, FileAttributes, FilePipePrinterAccessMask, ImpersonationLevel, Open, ShareAccess, ) from smbprotocol.session import Session from smbprotocol.tree import TreeConnect server = "dummy_server" username = "username" password = "Passord" share = r"\\dummy_server\testsamba" source_file_name = "dummy.txt" destination_path = "file_name.txt" connection = Connection(uuid.uuid4(), server) connection.connect() try: session = Session(connection, username, password) session.connect() tree = TreeConnect(session, share) tree.connect() # 打开源文件读取 source_file_open = Open(tree, source_file_name) source_file_info = source_file_open.create( ImpersonationLevel.Impersonation, FilePipePrinterAccessMask.GENERIC_READ, FileAttributes.FILE_ATTRIBUTE_NORMAL, ShareAccess.FILE_SHARE_READ, CreateDisposition.FILE_OPEN, CreateOptions.FILE_NON_DIRECTORY_FILE, ) file_bytes = source_file_open.end_of_file file_content = source_file_open.read(0, file_bytes) source_file_open.close() # 打开并写入目标文件 destination_file_open = Open(tree, destination_path) destination_file_info = destination_file_open.create( ImpersonationLevel.Impersonation, FilePipePrinterAccessMask.GENERIC_WRITE, FileAttributes.FILE_ATTRIBUTE_NORMAL, ShareAccess.FILE_SHARE_WRITE, # FILE_OVERWRITE_IF:文件存在则覆盖,不存在则创建 CreateDisposition.FILE_OVERWRITE_IF, CreateOptions.FILE_NON_DIRECTORY_FILE, ) destination_file_open.write(file_content) destination_file_open.close() # 写完后关闭文件 except Exception as err: print(err) finally: connection.disconnect()
关键修改说明
- 添加目标文件的
create()调用:这是核心修复,通过该方法向服务器发起创建/打开文件的请求,获取有效的文件句柄。 - 设置正确的权限和参数:
GENERIC_WRITE:授予写入权限FILE_OVERWRITE_IF:确保文件不存在时创建,存在时覆盖(若需避免覆盖,可改为FILE_CREATE,但此时文件已存在会报错)FILE_SHARE_WRITE:允许其他进程同时写入该文件(可根据需求调整)
- 关闭目标文件:写入完成后调用
close()释放资源
内容的提问来源于stack exchange,提问作者Sagar Patil
相关产品推荐
相关产品推荐

