smb:// URL Support in pysmb
Starting from pysmb version 1.0.4, application developers can utilize smb:// URLs with pysmb and urllib2 python package. One benefit from this is that if your existing application already supports downloads via other protocols like http or ftp, you can "upgrade" your application to support downloads from Windows shared folders or from Samba servers by making small modifications to your existing code.
pysmb tries to follow the smb URL scheme proposed in the IETF draft which is not much different from other standard URL schemes like http and ftp. In short, your smb URL should follow this format -
Sample File Retrieving Code
The following code illustrates a simple file retrieval operation from the remote server at 192.168.1.1. The userID and password are embedded in the URL and will be properly parsed by the SMBHandler for authentication with the remote server.
import urllib2 from smb.SMBHandler import SMBHandler director = urllib2.build_opener(SMBHandler) fh = director.open('smb://myuserID:email@example.com/sharedfolder/rfc1001.txt') # Process fh like a file-like object and then close it. fh.close()
The most important line is to register the SMBHandler class with the urllib2 library via the urllib2.build_opener() method. Note that there are other ways to register additional handlers, but this is the most straightforward method (in my opinion).
File Uploading to Remote Servers
In addition to file retrieval/download, pysmb also supports uploads to the remote servers. The following code example helps to illustrate a simple file upload operation.
import urllib2 from smb.SMBHandler import SMBHandler file_fh = open('local_file.dat', 'rb') director = urllib2.build_opener(SMBHandler) fh = director.open('smb://myuserID:firstname.lastname@example.org/sharedfolder/upload_file.dat', data = file_fh) # Reading from fh will only return an empty string fh.close()
The URL used is similar to that used in the file retrieval operation. However, observe that the open() method accepts a data parameter pointing to an opened file object. With this parameter, pysmb will perform a file upload operation instead of the usual file retrieval operation.
I hope the above 2 examples provide a quick insight on how to use pysmb and urllib2 in your application. If you need more advanced operations like folder creation and file deletion, pysmb already has built-in support for these via the SMBConnection class (synchronous I/O implementation) and SMBProtocol class (Twisted protocol implementation).