Example of pysmb
Asked Answered
C

4

15

Could you give me an example of using pysmb library to connect to some samba server? I've read there's class smb.SMBConnection.SMBConnection(username, password, my_name, remote_name, domain='', use_ntlm_v2=True) but i can't figure out how to use it

Courtroom answered 20/4, 2012 at 15:7 Comment(0)
A
20

I have been using pysmb for network shares enumeration lately, and found that it is not so easy to find good / complete examples. I'd refer you to a small script that I wrote for enumerating smb shares with pysmb: https://github.com/n3if/scripts/tree/master/smb_enumerator

For the sake of completeness, also, I post here the code snippet that accomplishes the connection and enumeration:

from smb import SMBConnection

try:
    conn = SMBConnection(username,password,'name',system_name,domain,use_ntlm_v2=True,
                         sign_options=SMBConnection.SIGN_WHEN_SUPPORTED,
                         is_direct_tcp=True) 
    connected = conn.connect(system_name,445)

    try:
        Response = conn.listShares(timeout=30)  # obtain a list of shares
        print('Shares on: ' + system_name)

        for i in range(len(Response)):  # iterate through the list of shares
            print("  Share[",i,"] =", Response[i].name)

            try:
                # list the files on each share
                Response2 = conn.listPath(Response[i].name,'/',timeout=30)
                print('    Files on: ' + system_name + '/' + "  Share[",i,"] =",
                                       Response[i].name)
                for i in range(len(Response2)):
                    print("    File[",i,"] =", Response2[i].filename)
            except:
                print('### can not access the resource')
    except:
        print('### can not list shares')    
except:
    print('### can not access the system')
Apis answered 8/5, 2015 at 14:25 Comment(2)
What if samba server has a 'GUEST' login. what to provide for username and password field in that case?Isolde
I'd say User=GUEST and Password='' but I should try it.Apis
V
8

The SMBConnection class will allow you to access the files on the remote Samba server in blocking mode.

To retrieve the list of the files in a shared folder on the remote server,

from smb.SMBConnection import SMBConnection
conn = SMBConnection(userid, password, client_machine_name, remote_machine_name, use_ntlm_v2 = True)
conn.connect(server_ip, 139)
filelist = conn.listPath('shared_folder_name', '/')

The returned filelist will be a list of SharedFile instances.

More examples can be found in the tests/SMBConnectionTests folder in the pysmb source package.

Vigilant answered 25/4, 2012 at 4:57 Comment(1)
Thanks. What are the client_machine_name, and remote_machine_name variables even supposed to look like? Which part of the address do I use? do I include "smb://" in the remote name?Ardis
M
5

I had a challenging time figuring out how to use pysmb module, but managed to get it working.

I'm using Python 3.10.15 on Windows 10 64-bit, using pysmb to connect to a network share within an enterprise domain. For my example, assume the following network share path using full UNC notation:

\\SHARENAME\RootDirectory\Subdirectory

Somethings to consider when using the SMBConnection Class:

  1. my_name string can be anything, even blank "". I used socket.gethostname()

  2. remote_name string must be the hostname of the network share (ie: SHARENAME from above example)

  3. ip string can be the network share's IP address (such as using socket.gethostbyname("SHARENAME") or the same name used for remote_name

  4. service_name string is a root directory under remote_name (ie: RootDirectory from above example)

  5. path string is the subdirectories under service_name (ie: Subdirectory from above example.

    • path string can contain \\ or / to signify a subdirectory. You can even use it mixed (ex: \\Subdirectory/SubSubdirectory)

See SharedFile Class for a list of attributes that is available when using listPath()

from smb.base import SharedFile
from smb.SMBConnection import SMBConnection

listSharedFileObj = []

# Using context manager to automatically close connection with code block finishes
with SMBConnection("username", "password", "my_name", "remote_name", "MYDOMAIN") as smbconn:
    # "You must call this method before attempting any of the file operations with the remote server."
    # https://pysmb.readthedocs.io/en/latest/api/smb_SMBConnection.html#smb.SMBConnection.SMBConnection.connect
    smbconn.connect("IP address or remote_name")

    # Returns: A list of "smb.base.SharedFile" instances
    # https://pysmb.readthedocs.io/en/latest/api/smb_SMBConnection.html#smb.SMBConnection.SMBConnection.listPath
    listSharedFileObj = smbconn.listPath("ROOTDIRECTORY", "/Subdirectory/SubSubdirectory")

# Pre annotate for type-hinting SharedFile object
item: SharedFile

for item in listSharedFileObj:
    print(item.filename)

Mollymollycoddle answered 28/9, 2022 at 16:13 Comment(0)
R
3

For example you want to store a file via pysmb same as this:

from smb.SMBConnection import SMBConnection

file_obj = open('image.png', 'rb')

connection = SMBConnection(username=username,
                           password=password,
                           remote_name=remote_name,  # It's net bios  name
                           domain=domain,
                           use_ntlm_v2=True)

connection.connect(ip=host)  # The IP of file server

connection.storeFile(service_name=service_name,  # It's the name of shared folder
                     path=path,
                     file_obj=file_obj)
connection.close()


Riddick answered 27/12, 2020 at 7:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.