def download(self, remoteFile, localPath, createMissingFolders): try: smbclient.register_session(self.host, username=self.username, password=self.password, connection_timeout=30) except Exception as e: self.error = str(e) return False try: if createMissingFolders: splitChar = "\\" if splitChar not in localPath: splitChar = "/" if not os.path.isdir(localPath.rsplit(splitChar, 1)[0]): os.makedirs(localPath.rsplit(splitChar, 1)[0]) with open(localPath, mode="wb") as f: with smbclient.open_file("\\{0}\{1}".format( self.host, remoteFile), mode="rb") as remoteFile: while True: part = remoteFile.read(4096) if not part: break f.write(part) smbclient.delete_session(self.host) return True except Exception as e: self.error = str(e) smbclient.delete_session(self.host) return False
def smb_share(request, smb_real): # Use some non ASCII chars to test out edge cases by default. share_path = u"%s\\%s" % (smb_real[request.param[1]], u"Pýtæs†-[%s] 💩" % time.time()) delete_session(smb_real[2]) # Test out forward slashes also work with the share-encrypted test if request.param[0] == 'share-encrypted': share_path = share_path.replace('\\', '/') mkdir(share_path, username=smb_real[0], password=smb_real[1], port=smb_real[3]) try: yield share_path finally: rmtree(share_path, username=smb_real[0], password=smb_real[1], port=smb_real[3])
def upload(self,localFile,remotePath): try: smbclient.register_session(self.host, username=self.username, password=self.password, connection_timeout=30) except Exception as e: self.error = str(e) return False # single file if not os.path.isdir(localFile): try: with open(localFile, mode="rb") as f: with smbclient.open_file("\\{0}\{1}".format(self.host,remotePath), mode="wb") as remoteFile: while True: part = f.read(4096) if not part: break remoteFile.write(part) except Exception as e: self.error = str(e) smbclient.delete_session(self.host) return False smbclient.delete_session(self.host) return True # Directory else: try: smbclient.mkdir("\\{0}\{1}".format(self.host,remotePath)) except OSError as e: if e.errno != errno.EEXIST: return False for root, dirs, files in os.walk(localFile): for dir in dirs: fullPath = os.path.join(root,dir) fullPath=fullPath.replace("/","\\") try: smbclient.mkdir("\\{0}\{1}\{2}".format(self.host,remotePath,fullPath[len(localFile)+1:])) except OSError as e: if e.errno != errno.EEXIST: return False for _file in files: try: fullPath = os.path.join(root,_file) with open(fullPath, mode="rb")as f: fullPath=fullPath.replace("/","\\") with smbclient.open_file("\\{0}\{1}\{2}".format(self.host,remotePath,fullPath[len(localFile)+1:]), mode="wb") as remoteFile: while True: part = f.read(4096) if not part: break remoteFile.write(part) except Exception as e: self.error = str(e) smbclient.delete_session(self.host) return False smbclient.delete_session(self.host) return True return False
def disconnect(self): if self.client: self.client = None smbclient.delete_session(self.host)