Not able to copy the file in the server from one file to another using smbprotocol

128 views Asked by At
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"

# Extract the file name from the source file path
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()

    # Open the source file for reading
    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

    # Read the content of the source file
    file_content = source_file_open.read(0, file_bytes)
    source_file_open.close()

    # write content to file
    destination_file_open = Open(tree, destination_path)
    print(destination_file_open.file_attributes)
    destination_file_open.write(file_content)

except Exception as err:
    print(err)

finally:
    connection.disconnect()

> Traceback (most recent call last):   File
> "C:\projects\pythonProject\smbdemo.py", line 55, in <module>
>     destination_file_open.write(file_content)   File "C:\Users\demo\.virtualenvs\pythonProject-l6U0AM3l\lib\site-packages\smbprotocol\open.py",
> line 1331, in write
>     return self._write_response(request, wait)   File "C:\Users\demo\.virtualenvs\pythonProject-l6U0AM3l\lib\site-packages\smbprotocol\open.py",
> line 1339, in _write_response
>     response = self.connection.receive(request, wait=wait)   File "C:\Users\demo\.virtualenvs\pythonProject-l6U0AM3l\lib\site-packages\smbprotocol\connection.py",
> line 1095, in receive
>     raise SMBResponseException(response) smbprotocol.exceptions.FileClosed: Received unexpected status from the
> server: An I/O request other than close and several other special case
> operations was attempted using a file object that had already been
> closed. (3221225768) STATUS_FILE_CLOSED: 0xc0000128
1

There are 1 answers

2
Tim Roberts On

The low-level Open call does not actually open the file. It just opens a file "session". You need to make a separate create call, as you did with the source file.

You should probably look at the smbclient module in that same package, which takes care of these low-level details for you.