Learning Python Network Programming

(Sean Pound) #1
Chapter 5

This module provides an SMBConnection class, where you can pass the necessary
parameters for accessing an SMB/CIFS share. For example, the following code will
help you to access a file-share:


from smb.SMBConnection import SMBConnection
smb_connection = SMBConnection(username, password,
client_machine_name, server_name, use_ntlm_v2 = True,
domain='WORKGROUP', is_direct_tcp=True)

If the preceding works, then the following assertion will be true:


assert smb_connection.connect(server_ip, 445)

You can list the shared files by using the listShares() method:


shares = smb_connection.listShares()
for share in shares:
print share.name

If you can use the tmpfile module copying a file from your windows share. For
example, if you create a file in the C:\Share\test.rtf path, then the additional
code shown here will copy that file by using the SMB protocol:


import tempfile
files = smb_connection.listPath(share.name, '/')

for file in files:
print file.filename

file_obj = tempfile.NamedTemporaryFile()
file_attributes, filesize = smb_connection.retrieveFile('Share',
'/test.rtf', file_obj)
file_obj.close()

If we put the entire code into a single source file, then it will look like the
following listing:


#!/usr/bin/env python
import tempfile
from smb.SMBConnection import SMBConnection

SAMBA_USER_ID = 'FaruqueSarker'
PASSWORD = 'PASSWORD'
CLIENT_MACHINE_NAME = 'debian6box'
SAMBA_SERVER_NAME = 'FARUQUESARKER'
SERVER_IP = '10.0.2.2'
Free download pdf