问题
I have remote server with some files.
smb://ftpsrv/public/
I can be authorized there as anonymous user. In java I could simply write such code
SmbFile root = new SmbFile(SMB_ROOT);
And get ability to work with files inside(it is all what I need, one row!), but I can't find how to manage with this task in python3, there are a lot of resources, but I think they are not relevant for me, because they are frequently tailored for python2 and old approaches. Is there some simple way, similar to java code above?
Or can somebody provide real working solution if, for example, I want to access file fgg.txt
in smb://ftpsrv/public/
folder. Is there really handy lib to tackle with this problem?
For example on site
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()
Am I seriously need to provide all of these details conn = SMBConnection(userID, password, client_machine_name, server_name, use_ntlm_v2 = True)
?
回答1:
A simple example of opening a file using urllib and pysmb in Python 3
import urllib
from smb.SMBHandler import SMBHandler
opener = urllib.request.build_opener(SMBHandler)
fh = opener.open('smb://host/share/file.txt')
data = fh.read()
fh.close()
I haven't got an anonymous SMB share ready to test it with, but this code should work.
urllib2 is the python 2 package, in python 3 it was renamed to just urllib and some stuff got moved around.
来源:https://stackoverflow.com/questions/49493699/access-remote-files-on-server-with-smb-protocol-python3