# SMBConnection Class

The SMBConnection is suitable for developers who wish to use pysmb to perform file operations with a remote SMB/CIFS server sequentially.

Each file operation method, when invoked, will block and return after it has completed or has encountered an error.

## Example

The following illustrates a simple file retrieving implementation.:

    import tempfile
    from smb.SMBConnection import SMBConnection

    # There will be some mechanism to capture userID, password, client_machine_name, server_name and server_ip
    # client_machine_name can be an arbitary ASCII string
    # server_name should match the remote machine name, or else the connection will be rejected
    conn = SMBConnection(userID, password, client_machine_name, server_name, use_ntlm_v2 = True)
    assert conn.connect(server_ip, 139)

    file_obj = tempfile.NamedTemporaryFile()
    file_attributes, filesize = conn.retrieveFile('smbtest', '/rfc1001.txt', file_obj)

    # Retrieved file contents are inside file_obj
    # Do what you need with the file_obj and then close it
    # Note that the file obj is positioned at the end-of-file,
    # so you might need to perform a file_obj.seek() if you need
    # to read from the beginning
    file_obj.close()

## SMB2 Support

Starting from pysmb 1.1.0, pysmb will utilize SMB2 protocol for communication if the remote SMB/CIFS service supports SMB2. Otherwise, it will fallback automatically back to using SMB1 protocol.

To disable SMB2 protocol in pysmb, set the SUPPORT_SMB2 flag in the smb_structs module to False before creating the SMBConnection instance.:

    from smb import smb_structs
    smb_structs.SUPPORT_SMB2 = False

## Caveats

- It is not meant to be used asynchronously.

- A single SMBConnection instance should not be used to perform more than one operation concurrently at the same time.

- Do not keep a SMBConnection instance “idle” for too long, i.e. keeping a SMBConnection instance but not using it. Most SMB/CIFS servers have some sort of keepalive mechanism and impose a timeout limit. If the clients fail to respond within the timeout limit, the SMB/CIFS server may disconnect the client.

class smb.SMBConnection.SMBConnection(username, password, my_name, remote_name, domain='', use_ntlm_v2=True, sign_options=2, is_direct_tcp=False)
  __init__(username, password, my_name, remote_name, domain='', use_ntlm_v2=True, sign_options=2, is_direct_tcp=False)

    Create a new SMBConnection instance.

    username and password are the user credentials required to authenticate the underlying SMB connection with the remote server. password can be a string or a callable returning a string. File operations can only be proceeded after the connection has been authenticated successfully.

    Note that you need to call connect method to actually establish the SMB connection to the remote server and perform authentication.

    The default TCP port for most SMB/CIFS servers using NetBIOS over TCP/IP is 139. Some newer server installations might also support Direct hosting of SMB over TCP/IP; for these servers, the default TCP port is 445.

    Parameters:

      - my_name (string) – The local NetBIOS machine name that will identify where this connection is originating from. You can freely choose a name as long as it contains a maximum of 15 alphanumeric characters and does not contain spaces and any of `\/:*?";|+`

      - remote_name (string) – The NetBIOS machine name of the remote server. On windows, you can find out the machine name by right-clicking on the “My Computer” and selecting “Properties”. This parameter must be the same as what has been configured on the remote server, or else the connection will be rejected.

      - domain (string) – The network domain. On windows, it is known as the workgroup. Usually, it is safe to leave this parameter as an empty string.

      - use_ntlm_v2 (boolean) – Indicates whether pysmb should be NTLMv1 or NTLMv2 authentication algorithm for authentication. The choice of NTLMv1 and NTLMv2 is configured on the remote server, and there is no mechanism to auto-detect which algorithm has been configured. Hence, we can only “guess” or try both algorithms. On Sambda, Windows Vista and Windows 7, NTLMv2 is enabled by default. On Windows XP, we can use NTLMv1 before NTLMv2.

      - sign_options (int) – Determines whether SMB messages will be signed. Default is SIGN_WHEN_REQUIRED. If SIGN_WHEN_REQUIRED (value=2), SMB messages will only be signed when remote server requires signing. If SIGN_WHEN_SUPPORTED (value=1), SMB messages will be signed when remote server supports signing but not requires signing. If SIGN_NEVER (value=0), SMB messages will never be signed regardless of remote server’s configurations; access errors will occur if the remote server requires signing.

      - is_direct_tcp (boolean) – Controls whether the NetBIOS over TCP/IP (is_direct_tcp=False) or the newer Direct hosting of SMB over TCP/IP (is_direct_tcp=True) will be used for the communication. The default parameter is False which will use NetBIOS over TCP/IP for wider compatibility (TCP port: 139).

  close()

    Terminate the SMB connection (if it has been started) and release any sources held by the underlying socket.

  connect(ip, port=139, sock_family=None, timeout=60)

    Establish the SMB connection to the remote SMB/CIFS server.

    You must call this method before attempting any of the file operations with the remote server. This method will block until the SMB connection has attempted at least one authentication.

    Parameters:

      - port – Defaults to 139. If you are using direct TCP mode (is_direct_tcp=true when creating this SMBConnection instance), use 445.

      - sock_family – In Python 3.x, use None as we can infer the socket family from the provided ip. In Python 2.x, it must be either socket.AF_INET or socket.AF_INET6.

    Returns:

      A boolean value indicating the result of the authentication atttempt: True if authentication is successful; False, if otherwise.

  createDirectory(service_name, path, timeout=30)

    Creates a new directory path on the service_name.

    Parameters:

      - service_name (string/unicode) – Contains the name of the shared folder.

      - path (string/unicode) – The path of the new folder (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path.

    Returns:

      None

  deleteDirectory(service_name, path, timeout=30)

    Delete the empty folder at path on service_name

    Parameters:

      - service_name (string/unicode) – Contains the name of the shared folder.

      - path (string/unicode) – The path of the to-be-deleted folder (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path.

    Returns:

      None

  deleteFiles(service_name, path_file_pattern, delete_matching_folders=False, timeout=30)

    Delete one or more regular files. It supports the use of wildcards in file names, allowing for deletion of multiple files in a single request.

    If delete_matching_folders is True, immediate sub-folders that match the path_file_pattern will be deleted recursively.

    Parameters:

      - service_name (string/unicode) – Contains the name of the shared folder.

      - path_file_pattern (string/unicode) – The pathname of the file(s) to be deleted, relative to the service_name. Wildcards may be used in th filename component of the path. If your path/filename contains non-English characters, you must pass in an unicode string.

    Returns:

      None

  echo(data, timeout=10)

    Send an echo command containing data to the remote SMB/CIFS server. The remote SMB/CIFS will reply with the same data.

    Parameters:

      data (bytes) – Data to send to the remote server. Must be a bytes object.

    Returns:

      The data parameter

  getAttributes(service_name, path, timeout=30)

    Retrieve information about the file at path on the service_name.

    Parameters:

      - service_name (string/unicode) – the name of the shared folder for the path

      - path (string/unicode) – Path of the file on the remote server. If the file cannot be opened for reading, an OperationFailure will be raised.

    Returns:

      A smb.base.SharedFile instance containing the attributes of the file.

  getSecurity(service_name, path, timeout=30)

    Retrieve the security descriptor of the file at path on the service_name.

    Parameters:

      - service_name (string/unicode) – the name of the shared folder for the path

      - path (string/unicode) – Path of the file on the remote server. If the file cannot be opened for reading, an OperationFailure will be raised.

    Returns:

      A `smb.security_descriptors.SecurityDescriptor` instance containing the security information of the file.

  listPath(service_name, path, search=65591, pattern='*', timeout=30)

    Retrieve a directory listing of files/folders at path

    For simplicity, pysmb defines a “normal” file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. It ignores other attributes like compression, indexed, sparse, temporary and encryption.

    Note that the default search parameter will query for all read-only (SMB_FILE_ATTRIBUTE_READONLY), hidden (SMB_FILE_ATTRIBUTE_HIDDEN), system (SMB_FILE_ATTRIBUTE_SYSTEM), archive (SMB_FILE_ATTRIBUTE_ARCHIVE), normal (SMB_FILE_ATTRIBUTE_INCL_NORMAL) files and directories (SMB_FILE_ATTRIBUTE_DIRECTORY). If you do not need to include “normal” files in the result, define your own search parameter without the SMB_FILE_ATTRIBUTE_INCL_NORMAL constant. SMB_FILE_ATTRIBUTE_NORMAL should be used by itself and not be used with other bit constants.

    Parameters:

      - service_name (string/unicode) – the name of the shared folder for the path

      - path (string/unicode) – path relative to the service_name where we are interested to learn about its files/sub-folders.

      - search (integer) – integer value made up from a bitwise-OR of SMB_FILE_ATTRIBUTE_xxx bits (see smb_constants.py).

      - pattern (string/unicode) – the filter to apply to the results before returning to the client.

    Returns:

      A list of smb.base.SharedFile instances.

  listShares(timeout=30)

    Retrieve a list of shared resources on remote server.

    Returns:

      A list of smb.base.SharedDevice instances describing the shared resource

  listSnapshots(service_name, path, timeout=30)

    Retrieve a list of available snapshots (shadow copies) for path.

    Note that snapshot features are only supported on Windows Vista Business, Enterprise and Ultimate, and on all Windows 7 editions.

    Parameters:

      - service_name (string/unicode) – the name of the shared folder for the path

      - path (string/unicode) – path relative to the service_name where we are interested in the list of available snapshots

    Returns:

      A list of python datetime.DateTime instances in GMT/UTC time zone

  rename(service_name, old_path, new_path, timeout=30)

    Rename a file or folder at old_path to new_path shared at service_name. Note that this method cannot be used to rename file/folder across different shared folders

    old_path and new_path are string/unicode referring to the old and new path of the renamed resources (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path.

    Parameters:

      service_name (string/unicode) – Contains the name of the shared folder.

    Returns:

      None

  resetFileAttributes(service_name, path_file_pattern, file_attributes=128, timeout=30)

    Reset file attributes of one or more regular files or folders. It supports the use of wildcards in file names, allowing for unlocking of multiple files/folders in a single request. This function is very helpful when deleting files/folders that are read-only. By default, it sets the ATTR_NORMAL flag, therefore clearing all other flags. (See https://msdn.microsoft.com/en-us/library/cc232110.aspx for further information)

    Note: this function is currently only implemented for SMB2!

    Parameters:

      - service_name (string/unicode) – Contains the name of the shared folder.

      - path_file_pattern (string/unicode) – The pathname of the file(s) to be deleted, relative to the service_name. Wildcards may be used in the filename component of the path. If your path/filename contains non-English characters, you must pass in an unicode string.

      - file_attributes (int) – The desired file attributes to set. Defaults to ATTR_NORMAL.

    Returns:

      None

  retrieveFile(service_name, path, file_obj, timeout=30, show_progress=False, tqdm_kwargs={})

    Retrieve the contents of the file at path on the service_name and write these contents to the provided file_obj.

    Use retrieveFileFromOffset() method if you wish to specify the offset to read from the remote path and/or the number of bytes to write to the file_obj.

    Parameters:

      - service_name (string/unicode) – the name of the shared folder for the path

      - path (string/unicode) – Path of the file on the remote server. If the file cannot be opened for reading, an OperationFailure will be raised.

      - file_obj – A file-like object that has a write method. Data will be written continuously to file_obj until EOF is received from the remote service. In Python3, this file-like object must have a write method which accepts a bytes parameter.

      - show_progress (bool) – If True, a progress bar will be shown to reflect the current file operation progress.

    Returns:

      A 2-element tuple of ( file attributes of the file on server, number of bytes written to file_obj ). The file attributes is an integer value made up from a bitwise-OR of SMB_FILE_ATTRIBUTE_xxx bits (see smb_constants.py)

  retrieveFileFromOffset(service_name, path, file_obj, offset=0, max_length=- 1, timeout=30, show_progress=False, tqdm_kwargs={})

    Retrieve the contents of the file at path on the service_name and write these contents to the provided file_obj.

    Parameters:

      - service_name (string/unicode) – the name of the shared folder for the path

      - path (string/unicode) – Path of the file on the remote server. If the file cannot be opened for reading, an OperationFailure will be raised.

      - file_obj – A file-like object that has a write method. Data will be written continuously to file_obj up to max_length number of bytes. In Python3, this file-like object must have a write method which accepts a bytes parameter.

      - offset (integer/long) – the offset in the remote path where the first byte will be read and written to file_obj. Must be either zero or a positive integer/long value.

      - max_length (integer/long) – maximum number of bytes to read from the remote path and write to the file_obj. Specify a negative value to read from offset to the EOF. If zero, the method returns immediately after the file is opened successfully for reading.

      - show_progress (bool) – If True, a progress bar will be shown to reflect the current file operation progress.

    Returns:

      A 2-element tuple of ( file attributes of the file on server, number of bytes written to file_obj ). The file attributes is an integer value made up from a bitwise-OR of SMB_FILE_ATTRIBUTE_xxx bits (see smb_constants.py)

  storeFile(service_name, path, file_obj, timeout=30, show_progress=False, tqdm_kwargs={})

    Store the contents of the file_obj at path on the service_name. If the file already exists on the remote server, it will be truncated and overwritten.

    Parameters:

      - service_name (string/unicode) – the name of the shared folder for the path

      - path (string/unicode) – Path of the file on the remote server. If the file at path does not exist, it will be created. Otherwise, it will be overwritten. If the path refers to a folder or the file cannot be opened for writing, an OperationFailure will be raised.

      - file_obj – A file-like object that has a read method. Data will read continuously from file_obj until EOF. In Python3, this file-like object must have a read method which returns a bytes parameter.

      - show_progress (bool) – If True, a progress bar will be shown to reflect the current file operation progress.

    Returns:

      Number of bytes uploaded

  storeFileFromOffset(service_name, path, file_obj, offset=0, truncate=False, timeout=30, show_progress=False, tqdm_kwargs={})

    Store the contents of the file_obj at path on the service_name.

    Parameters:

      - service_name (string/unicode) – the name of the shared folder for the path

      - path (string/unicode) – Path of the file on the remote server. If the file at path does not exist, it will be created. If the path refers to a folder or the file cannot be opened for writing, an OperationFailure will be raised.

      - file_obj – A file-like object that has a read method. Data will read continuously from file_obj until EOF.

      - offset – Long integer value which specifies the offset in the remote server to start writing. First byte of the file is 0.

      - truncate – Boolean value. If True and the file exists on the remote server, it will be truncated first before writing. Default is False.

      - show_progress (bool) – If True, a progress bar will be shown to reflect the current file operation progress.

    Returns:

      the file position where the next byte will be written.

  SIGN_NEVER = 0

    SMB messages will never be signed regardless of remote server’s configurations; access errors will occur if the remote server requires signing.

  SIGN_WHEN_REQUIRED = 2

    SMB messages will only be signed when remote server requires signing.

  SIGN_WHEN_SUPPORTED = 1

    SMB messages will be signed when remote server supports signing but not requires signing.

  property isUsingSMB2

    A convenient property to return True if the underlying SMB connection is using SMB2 protocol.