本文整理汇总了Python中smb.SMBConnection.SMBConnection.retrieveFile方法的典型用法代码示例。如果您正苦于以下问题:Python SMBConnection.retrieveFile方法的具体用法?Python SMBConnection.retrieveFile怎么用?Python SMBConnection.retrieveFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类smb.SMBConnection.SMBConnection
的用法示例。
在下文中一共展示了SMBConnection.retrieveFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: SmbClient
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import retrieveFile [as 别名]
class SmbClient(object):
def __init__(self,ip,username,password,sharename):
self.ip = ip
self.username = username
self.password = password
self.sharename = sharename
def connect(self):
self.server = SMBConnection(self.username,
self.password,client,netbios_name,use_ntlm_v2=True)
self.server.connect(self.ip,139)
def upload(self,file):
data = open(file,'rb')
file = '/' + file
self.server.storeFile(self.sharename,file,data)
print "file has been uploaded"
def download(self,file):
fileobj = open(file,'wb')
self.server.retrieveFile(self.sharename,fileobj)
print "file has been downloaded in current dir"
def delete(self,file):
'remove file from remote share'
file = '/' + file
self.server.deleteFiles(self.sharename,file)
def list(self):
' list files of remote share '
filelist = self.server.listPath(self.sharename,'/')
for f in filelist:
print f.filename
示例2: file_connection
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import retrieveFile [as 别名]
def file_connection():
IP = sys.argv[1]
shareName = sys.argv[2]
inputFile = sys.argv[3]
port = 139
conn = SMBConnection("","","","")
conn.connect(IP,port)
fileObj = tempfile.NamedTemporaryFile()
conn.retrieveFile(shareName,inputFile,fileObj)
return fileObj
示例3: return_sampleIDs
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import retrieveFile [as 别名]
def return_sampleIDs():
sampleIDs = []
query = request.form['query']
mainLibraryFolder = request.form['mainLibraryFolder']
try:
conn = SMBConnection(username, password, myRequestIdentifier, serverName, domain=domain, use_ntlm_v2 = True)
conn.connect(host, port)
sampleSheetCSV = tempfile.NamedTemporaryFile()
pathTo = 'MiSeqOutput/'+mainLibraryFolder+'/SampleSheet.csv'
sampleSheetCSV_attributes, sampleSheetCSV_size = conn.retrieveFile(sharedFolder, pathTo, sampleSheetCSV)
sampleSheetCSV.seek(0)
fileContents = sampleSheetCSV.read()
uniqueLines = fileContents.replace("\r\n", '\n').replace("\r", '\n').split("\n")
counter = 0
for line in uniqueLines:
#sampleIDs.append(idtext(line, line))
if (line.startswith("[Data]") or counter==1):
counter+=1
continue
#Two lines after [Data] line, first sampleIDs is encountered
if (counter==2):
sampleID = line[:line.find(",")]
if (query.lower() in sampleID.lower()) and not sampleID=="": #Not blank line
sampleIDs.append(idtext(sampleID, sampleID))
except Exception as ex:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
return jsonify(result=(exc_type, fname, exc_tb.tb_lineno))
return jsonify(result=[e.serialize() for e in sampleIDs])
示例4: FileServerConnection
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import retrieveFile [as 别名]
class FileServerConnection(object):
"""Connection to a Samba file server"""
def __init__(self, ip, port, clientName, serverName, username, password):
self.conn = SMBConnection(username, password, clientName, serverName)
self.conn.connect(ip, port)
try:
shares = self.conn.listShares()
sharesStr = ", ".join("{0.name} ({0.comments})".format(s) for s in shares)
logging.info("Visible shares on {} ({}:{}): {}".format(serverName,
ip,
port,
sharesStr))
except smb.base.NotReadyError as e:
raise FileServerException(e)
def append(self, share, path, data):
try:
# Get the existing contents of the file.
file = StringIO()
try:
self.conn.retrieveFile(share, path, file)
except smb.smb_structs.OperationFailure as e:
# The file might not exist yet.
if not e.message.endswith("Unable to open file"):
# Something else went wrong.
raise
# Append the data.
file.write(data)
file.seek(0)
# NOTE: Apparently storeFile fails if the target file exists. It
# must be deleted first.
# TODO: Rename the old file instead of deleting until the store
# operation is completed succesfully?
try:
self.conn.deleteFiles(share, path)
except smb.smb_structs.OperationFailure as e:
# The file might not exist yet.
if not e.message.endswith("Delete failed"):
# Something else went wrong.
raise
self.conn.storeFile(share, path, file)
except smb.smb_structs.OperationFailure as e:
raise FileServerException(e.message)
示例5: run
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import retrieveFile [as 别名]
def run(options):
ip = options['ip']
port = options['port']
username = options['username']
password = options['password']
test = random.choice(config.SMB_FILES)
expected = test['checksum']
try:
n = NetBIOS()
hostname = n.queryIPForName(ip)[0]
n.close()
conn = SMBConnection(username, password, '', hostname, config.DOMAIN)
conn.connect(ip, port)
t = tempfile.TemporaryFile()
conn.retrieveFile(test['sharename'], test['path'], t)
except (SMBTimeout, socket.timeout):
logger.debug('Timeout')
return False
except NotReadyError:
logger.debug(ERROR_STRINGS['NotReadyError'] % (username, password))
return False
except (NotConnectedError, UnsupportedFeature, ProtocolError, OperationFailure) as e:
name = e.__class__.__name__
if name in ERROR_STRINGS:
logger.debug(ERROR_STRINGS[name] % e)
else:
logger.debug('%s: %s' % (name, e))
return False
sha1 = hashlib.sha1()
t.seek(0)
sha1.update(t.read())
t.close()
checksum = sha1.hexdigest()
if checksum == expected:
return True
else:
logger.debug('Check failed: output: %s | expected: %s' % (checksum, expected))
return False
示例6: __init__
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import retrieveFile [as 别名]
class smb_connector:
def __init__(self, ip, shared_directory, username, password):
self.connection = SMBConnection(username, password, "this_machine", "remote_machine", use_ntlm_v2=True, is_direct_tcp=True)
self.connection.connect(ip, 445)
self.shared_directory = shared_directory
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def close(self):
self.connection.close()
def file_contents(self, path):
with tempfile.NamedTemporaryFile() as file_obj:
self.connection.retrieveFile(self.shared_directory, path, file_obj)
file_obj.seek(0)
content = file_obj.read().decode('utf-8', 'ignore').translate({ord('\u0000'): None})
return content
def all_files_recursively(self, full_path, file_filter, directory_filter, relative_path=''):
whats_here = self.connection.listPath(self.shared_directory, full_path)
for file in whats_here:
file_path = os.path.join(full_path, file.filename)
file_relative_path = os.path.join(relative_path, file.filename)
if file.isDirectory:
if directory_filter(file.filename) and '.' not in file.filename:
yield from self.all_files_recursively(file_path, file_filter, directory_filter, file_relative_path)
elif file_filter(file.filename):
yield os.path.normpath(file_relative_path)
def write_file(self, path, contents):
with tempfile.NamedTemporaryFile() as file_obj:
bytes = file_obj.write(contents.encode('utf-8'))
file_obj.seek(0)
bytes = self.connection.storeFile(self.shared_directory, path, file_obj)
示例7: show_file
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import retrieveFile [as 别名]
def show_file(filename):
conn = SMBConnection(USERNAME, PASSWORD, MY_NAME, REMOTE_NAME, use_ntlm_v2=False)
conn.connect(SERVER_IP, PORT)
#This module implements a file-like class, StringIO, that reads and writes a string buffer (also known as memory files). See the description of file objects for operations (section File Objects). (For standard strings, see str and unicode.)
temp_fh = StringIO()
#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.
file_attributes, filesize = conn.retrieveFile('Share', '/ESAP/Hand-Out/' + filename, temp_fh)
conn.close()
#读取文件名字
localfile = filename.split('/')[-1]
#存到服务器
f = open(os.path.join(os.getcwd() + '/static/', localfile), 'w')
f.write(temp_fh.getvalue())
#读取服务器的文件
return redirect(url_for('static', filename=localfile), code=301)
示例8: copy_file_from
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import retrieveFile [as 别名]
def copy_file_from(server_name, file_path):
# set connection with smb server
conn = SMBConnection(ConfigHost.USERNAME, ConfigHost.PASSWORD, ConfigHost.CLIENT_NAME, server_name)
conn.connect(getBIOSIp(server_name)[0])
#with mounted(remote_dir, local_dir):
# shutil.copy(file_to_be_copied, local_dir)
try:
filename = path_leaf(file_path)
print filename
#data_file = open(filename, 'w')
data_file = tempfile.NamedTemporaryFile()
attr, size = conn.retrieveFile(ConfigHost.SHARE_DIR, file_path, data_file)
print size
data_file.close()
except Exception as e:
print e.message
示例9: SMB_client
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import retrieveFile [as 别名]
#.........这里部分代码省略.........
w = path+'/'
files = self.getRemoteDir(path, '*')
if files:
for file in files:
if file.filename[0] == '.':
continue
self.tree.append({'name':w+file.filename, 'isdir':file.isDirectory, 'size':file.file_size})
if file.isDirectory:
self.getRemoteTree(path=w+file.filename)
return self.tree
except Exception as e:
if self.print_errors:
print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
else:
self.error = 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + str(type(e).__name__) + str(e)
return None
def download(self, path, filename,buffersize=None,callback=None, local_path=None):
try:
self.error = None
#print('Download = ' + path + filename)
attr = self.conn.getAttributes(self.service_name, path+filename)
#print('Size = %.1f kB' % (attr.file_size / 1024.0))
#print('start download')
file_obj = BytesIO()
if local_path:
fw = open(local_path+filename, 'wb')
else:
fw = open(filename, 'wb')
offset = 0
transmit =0
while True:
if not buffersize:
file_attributes, filesize = self.conn.retrieveFile(self.service_name, path+filename, file_obj)
else:
file_attributes, filesize = self.conn.retrieveFileFromOffset(self.service_name, path+filename, file_obj,offset=offset,max_length=buffersize)
if callback:
transmit = transmit + filesize
callback(transmit)
file_obj.seek(offset)
for line in file_obj:
fw.write(line)
offset = offset + filesize
if (not buffersize) or (filesize == 0):
break
fw.close()
#print('download finished')
except Exception as e:
if self.print_errors:
print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
else:
self.error = 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + str(type(e).__name__) + str(e)
def upload(self, path, filename,buffersize=None,callback=None, local_path=None):
try:
self.error = None
#print('Upload = ' + path + filename)
#print('Size = %.1f kB' % (os.path.getsize(filename) / 1024.0))
#print('start upload')
if local_path:
file_obj = open(local_path+filename, 'rb')
else:
file_obj = open(filename, 'rb')
offset = 0
while True:
if not buffersize:
示例10: smb_open
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import retrieveFile [as 别名]
def smb_open(self, req):
global USE_NTLM, MACHINE_NAME
host = req.get_host()
if not host:
raise urllib2.URLError('SMB error: no host given')
host, port = splitport(host)
if port is None:
port = 139
else:
port = int(port)
# username/password handling
user, host = splituser(host)
if user:
user, passwd = splitpasswd(user)
else:
passwd = None
host = unquote(host)
user = user or ''
domain = ''
if ';' in user:
domain, user = user.split(';', 1)
passwd = passwd or ''
myname = MACHINE_NAME or self.generateClientMachineName()
n = NetBIOS()
names = n.queryIPForName(host)
if names:
server_name = names[0]
else:
raise urllib2.URLError('SMB error: Hostname does not reply back with its machine name')
path, attrs = splitattr(req.get_selector())
if path.startswith('/'):
path = path[1:]
dirs = path.split('/')
dirs = map(unquote, dirs)
service, path = dirs[0], '/'.join(dirs[1:])
try:
conn = SMBConnection(user, passwd, myname, server_name, domain=domain, use_ntlm_v2 = USE_NTLM)
conn.connect(host, port)
if req.has_data():
data_fp = req.get_data()
filelen = conn.storeFile(service, path, data_fp)
headers = "Content-length: 0\n"
fp = StringIO("")
else:
fp = self.createTempFile()
file_attrs, retrlen = conn.retrieveFile(service, path, fp)
fp.seek(0)
headers = ""
mtype = mimetypes.guess_type(req.get_full_url())[0]
if mtype:
headers += "Content-type: %s\n" % mtype
if retrlen is not None and retrlen >= 0:
headers += "Content-length: %d\n" % retrlen
sf = StringIO(headers)
headers = mimetools.Message(sf)
return addinfourl(fp, headers, req.get_full_url())
except Exception, ex:
raise urllib2.URLError, ('smb error: %s' % ex), sys.exc_info()[2]
示例11: FetchFile
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import retrieveFile [as 别名]
#.........这里部分代码省略.........
dpath = self._getLastFilePath(self._subPath)
path = dpath['path']
file = dpath['file']
#print 'path', path
#print 'file', file
self._filename = file
#
dlist = self._getFileList(path)
folderList = dlist[self.FOLDERLIST]
fileList = dlist[self.FILELIST]
if file.decode('utf-8') in folderList:
self._resourceType = TYPE_FOLDER
return TYPE_FOLDER
if file.decode('utf-8') in fileList:
self._resourceType = TYPE_FILE
return TYPE_FILE
return None
#if folder return filelist, if file return filepath.
def _getContent(self):
type = self._getFileType()
#print 'content type', type
if type == TYPE_FOLDER:
dfiles = self._getFileList()
#print 'dfiles', dfiles
#dfiles['type'] = TYPE_FOLDER
files = []
files.extend(dfiles[self.FOLDERLIST])
files.extend(dfiles[self.FILELIST])
return TYPE_FOLDER, str(files)
elif type == TYPE_FILE:
# return {'filepath':self._retrieveFile()}
tempResult = self._retrieveFile()
# return TYPE_FILE, self._retrieveFile()
return TYPE_FILE, tempResult
else:
return None, None
def _retrieveFile(self):
tempPath = SF_TEMPPATH
self.mkdir(tempPath)
import os
filename = self._addr.replace('/', '_')
tempPath = os.path.realpath(tempPath + filename)
import tempfile
with open(tempPath, 'wb+') as fo:
#fp = tempfile.NamedTemporaryFile()
fa, filesize = self._conn.retrieveFile(self._rootNode, self._subPath, fo)
#print 'filesize', filesize
#for line in fp:
# fo.write(line)
#fp.close()
fo.close()
return tempPath
def _detectFileType(self, fileType):
from const_file_type import GLOBAL_FILE_TYPE
if fileType == TYPE_FOLDER:
return GLOBAL_FILE_TYPE.SF
elif fileType == TYPE_FILE:
if self._addr.lower().endswith('.pdf'):
return GLOBAL_FILE_TYPE.PDF
elif self._addr.lower().endswith('.doc'):
return GLOBAL_FILE_TYPE.DOC
elif self._addr.lower().endswith('.docx'):
示例12: ProtocolSMB
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import retrieveFile [as 别名]
class ProtocolSMB(ILocation):
"""
Doku: http://packages.python.org/pysmb/api/smb_SMBConnection.html?highlight=listpath#smb.SMBConnection.SMBConnection.listPath
"""
_conn = None
def __del__(self):
self._conn.close()
def connect(self, username, password, ip):
""" remote connect smb """
from smb.SMBConnection import SMBConnection
self._conn = SMBConnection(username, password, my_name = "", remote_name = "", domain='', use_ntlm_v2=True)
return self._conn.connect(ip = ip, timeout = 5)
def listDir(self, path):
m = re.match('/.+?/(.+?)/(.+)', path)
share = m.group(1)
folder = m.group(2)
list = []
for item in self._conn.listPath(share, folder):
if item.isDirectory and item.filename[0] != '.':
list.append( item.filename )
return list
def listFile(self, path):
m = re.match('/.+?/(.+?)/(.+)', path)
share = m.group(1)
folder = m.group(2)
#filter = m.group(3)
list = []
for item in self._conn.listPath(share, folder):
if item.isDirectory == False:
list.append( item.filename )
return list
def readFile(self, filename):
m = re.match('/.+?/(.*?)/(.*)', filename)
share = m.group(1)
folder = m.group(2)
import tempfile
tmpfile = tempfile.TemporaryFile()
self._conn.retrieveFile(share, folder, tmpfile)
tmpfile.seek(0)
buffer = ""
try:
for line in tmpfile:
buffer +=line
finally:
tmpfile.close()
return buffer
def generate_path(self, a, *p):
chdir = a
for path in p:
chdir = chdir + '/' + path
return chdir
示例13: SMB_Connect
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import retrieveFile [as 别名]
def SMB_Connect(host,sharename,user,password,folder,writeable):
'''connects to a share with the given credentials and checks if it's writeable or not
host: hostname (FQDN)
sharename: Name of the share
username: username
password: password
writeable: if set to True, it will check if the share is writeable
'''
check_passed=False
check_file=''.join(['/', folder,'/nagioscheck.txt'])
hostname = host.split('.')
host_ip= socket.gethostbyname(host)
conn = SMBConnection(user, password, socket.gethostname(), hostname[0], use_ntlm_v2 = True)
try:
conn.connect(host_ip, 139)
except:
print "Connection to Host failed"
sys.exit(status['CRITICAL'])
if conn.auth_result:
#only check if share is listed
if not writeable:
shares = conn.listShares()
for share in shares:
if sharename == share.name:
print "Found ",share.name
check_passed = True
break
else:
#schreiben
check_value = "File Created from nagios "+str(datetime.now())
file_obj = tempfile.NamedTemporaryFile()
file_obj.write(check_value)
file_obj.flush()
file_obj.seek(0)
try:
conn.storeFile(sharename, check_file, file_obj)
except:
check_passed=False
file_obj.close()
#lesen
file_obj = tempfile.NamedTemporaryFile()
try:
file_attributes, filesize = conn.retrieveFile(sharename, check_file, file_obj)
file_obj.seek(0)
file_content= file_obj.read()
if file_content == check_value:
check_passed=True
except:
check_passed=False
file_obj.close()
conn.close()
#file loeschen
try:
conn = SMBConnection(user, password, socket.gethostname(), hostname[0], use_ntlm_v2 = True)
conn.connect(host_ip, 139)
conn.deleteFiles(sharename, check_file)
except Exception, e:
check_passed=False
conn.close()
示例14: CommonCIFSShare
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import retrieveFile [as 别名]
class CommonCIFSShare(object):
"""
Handle CIFS shares
"""
def __init__(self):
self.smb_conn = None
def com_cifs_connect(self, ip_addr, user_name='guest', user_password=''):
"""
Connect to share
"""
server_name = 'Server'
client_name = 'My Computer'
self.smb_conn = SMBConnection(user_name, user_password, client_name, server_name,
use_ntlm_v2=True)
self.smb_conn.connect(ip_addr, 139)
def com_cifs_share_list_by_connection(self):
"""
List shares
"""
share_names = []
for row_data in self.smb_conn.listShares():
share_names.append(row_data.name)
return share_names
def com_cifs_share_file_list_by_share(self, share_name, path_text='/'):
"""
List files in share
"""
file_names = []
for row_data in self.smb_conn.listPath(share_name, path_text):
common_global.es_inst.com_elastic_index('info', {'stuff': row_data.filename})
file_names.append(row_data.filename)
return file_names
def com_cifs_share_directory_check(self, share_name, dir_path):
"""
Verify smb directory
"""
# try due to fact invalid file/path freaks out the connection
try:
return self.smb_conn.getAttributes(share_name, dir_path).isDirectory
except:
pass
return False
def com_cifs_share_file_dir_info(self, share_name, file_path):
"""
Get specific path/file info
"""
return self.smb_conn.getAttributes(share_name, file_path)
def com_cifs_share_file_upload(self, file_path):
"""
Upload file to smb
"""
self.smb_conn.storeFile(os.path.join(
self.sharename, file_path), open(file_path, 'rb'))
def com_cifs_share_file_download(self, file_path):
"""
Download from smb
"""
self.smb_conn.retrieveFile(self.sharename, open(file_path, 'wb'))
def com_cifs_share_file_delete(self, share_name, file_path):
"""
Delete from smb
"""
self.smb_conn.deleteFiles(os.path.join(share_name, file_path))
def com_cifs_close(self):
"""
Close connection
"""
self.smb_conn.close()
def com_cifs_walk(self, share_name, file_path='/'):
"""
cifs directory walk
"""
dirs, nondirs = [], []
for name in self.smb_conn.listPath(share_name, file_path):
if name.isDirectory:
if name.filename not in ['.', '..']:
dirs.append(name.filename)
else:
nondirs.append(name.filename)
yield file_path, dirs, nondirs
for name in dirs:
# new_path = file_path + '\\' + name
# for ndx in self.com_cifs_walk(share_name, new_path):
for ndx in self.com_cifs_walk(share_name, os.path.join(file_path, name)):
yield ndx
示例15: smb_open
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import retrieveFile [as 别名]
def smb_open(self, req):
global USE_NTLM, MACHINE_NAME
host = req.get_host()
if not host:
raise urllib.error.URLError('SMB error: no host given')
host, port = splitport(host)
if port is None:
port = 139
else:
port = int(port)
# username/password handling
user, host = splituser(host)
if user:
user, passwd = splitpasswd(user)
else:
passwd = None
host = unquote(host)
user = user or ''
passwd = passwd or ''
myname = MACHINE_NAME or self.generateClientMachineName()
n = NetBIOS()
names = n.queryIPForName(host)
if names:
server_name = names[0]
else:
raise urllib.error.URLError('SMB error: Hostname does not reply back with its machine name')
path, attrs = splitattr(req.get_selector())
if path.startswith('/'):
path = path[1:]
dirs = path.split('/')
dirs = list(map(unquote, dirs))
service, path = dirs[0], '/'.join(dirs[1:])
try:
conn = SMBConnection(user, passwd, myname, server_name, use_ntlm_v2 = USE_NTLM)
conn.connect(host, port)
headers = email.message.Message()
if req.has_data():
data_fp = req.get_data()
filelen = conn.storeFile(service, path, data_fp)
headers.add_header('Content-length', '0')
fp = BytesIO(b"")
else:
fp = self.createTempFile()
file_attrs, retrlen = conn.retrieveFile(service, path, fp)
fp.seek(0)
mtype = mimetypes.guess_type(req.get_full_url())[0]
if mtype:
headers.add_header('Content-type', mtype)
if retrlen is not None and retrlen >= 0:
headers.add_header('Content-length', '%d' % retrlen)
return addinfourl(fp, headers, req.get_full_url())
except Exception as ex:
raise urllib.error.URLError('smb error: %s' % ex).with_traceback(sys.exc_info()[2])