def move( connection: SMBConnection, share_folder: str, file_path: str, input_file_path: str, temp_file_suffix=".tmp", ): logger.info( f"Moving {input_file_path} file to \\\\{connection.remote_name}\\{share_folder}{file_path}..." ) try: with open(input_file_path, "rb") as input_file: connection.storeFile(share_folder, f"{file_path}{temp_file_suffix}", input_file) except OperationFailure: raise Exception( f"Unable to write \\\\{connection.remote_name}\\{share_folder}{file_path}{temp_file_suffix}" ) if temp_file_suffix: try: connection.rename(share_folder, f"{file_path}{temp_file_suffix}", file_path) except OperationFailure: raise Exception( f"Unable to rename temp file into \\\\{connection.remote_name}\\{share_folder}{file_path}" ) logger.info(f"File copied. Removing {input_file_path} file...") os.remove(input_file_path) logger.info( f"{input_file_path} file moved within \\\\{connection.remote_name}\\{share_folder}{file_path}." )
def transfer(self, uid, old_code, new_code): """ Sync a child transfer with GP: rename pictures and log a note. """ # Retrieve configuration smb_user = config.get('smb_user') smb_pass = config.get('smb_pwd') smb_ip = config.get('smb_ip') smb_port = int(config.get('smb_port', 0)) if not (smb_user and smb_pass and smb_ip and smb_port): return False # Rename files in shared folder smb_conn = SMBConnection(smb_user, smb_pass, 'openerp', 'nas') if smb_conn.connect(smb_ip, smb_port): gp_old_pic_path = "{0}{1}/".format(config.get('gp_pictures'), old_code[:2]) gp_new_pic_path = "{0}{1}/".format(config.get('gp_pictures'), new_code[:2]) pic_files = smb_conn.listPath('GP', gp_old_pic_path) for file in pic_files: filename = file.filename if filename.startswith(old_code): new_name = filename.replace(old_code, new_code) smb_conn.rename('GP', gp_old_pic_path + filename, gp_new_pic_path + new_name) # Rename child code in GP tables self.query("UPDATE ENFANTS SET CODE = %s WHERE CODE = %s", [new_code, old_code]) self.query("UPDATE Poles SET CODESPE = %s WHERE CODESPE = %s", [new_code, old_code]) self.query("UPDATE Affectat SET CODESPE = %s WHERE CODESPE = %s", [new_code, old_code]) return True
def transfer(self, uid, old_code, new_code): """ Sync a child transfer with GP: rename pictures and log a note. """ # Retrieve configuration smb_user = config.get("smb_user") smb_pass = config.get("smb_pwd") smb_ip = config.get("smb_ip") smb_port = int(config.get("smb_port", 0)) if not (smb_user and smb_pass and smb_ip and smb_port): return False # Rename files in shared folder smb_conn = SMBConnection(smb_user, smb_pass, "openerp", "nas") if smb_conn.connect(smb_ip, smb_port): gp_old_pic_path = "{0}{1}/".format(config.get("gp_pictures"), old_code[:2]) gp_new_pic_path = "{0}{1}/".format(config.get("gp_pictures"), new_code[:2]) pic_files = smb_conn.listPath("GP", gp_old_pic_path) for file in pic_files: filename = file.filename if filename.startswith(old_code): new_name = filename.replace(old_code, new_code) smb_conn.rename("GP", gp_old_pic_path + filename, gp_new_pic_path + new_name) # Rename child code in Poles table self.query("UPDATE Poles SET CODESPE = %s WHERE CODESPE = %s", [old_code, new_code]) return True
def rename(self): conn = SMBConnection(self.username.get(), self.password.get(), self.my_name, self.domain_name, use_ntlm_v2=True, is_direct_tcp=True) conn.connect(self.remote_smb_IP.get(), int(self.port.get())) conn.rename(self.dir, self.display_path + '/' + ml.get(ml.curselection()), self.display_path + '/' + self.message.get())
def move( connection: SMBConnection, share_folder: str, file_path: str, input_file_path: str, temp_file_suffix=".tmp", timeout=30, write_to_new_folder_after=1, ): """ Move a local file to a Windows location. :param connection: Samba connection as returned by connect function. :param share_folder: Shared folder name. :param file_path: Expected full path to the file that should be created. Folders will be created if needed. :param input_file_path: Path to the file to move. :param temp_file_suffix: Suffix of the file while being copied. Default to ".tmp". :param timeout: Maximum amount of seconds to write the file. Default to 30 seconds. :param write_to_new_folder_after: Number of seconds to wait before writing file if folder needed to be created. Useful as Microsoft does not seems to release folder right away. Default to 1 second. """ logger.info( f"Moving {input_file_path} file to \\\\{connection.remote_name}\\{share_folder}{file_path}..." ) if _create_folders(connection, share_folder, os.path.dirname(file_path)): time.sleep(write_to_new_folder_after) try: with open(input_file_path, "rb") as input_file: connection.storeFile(share_folder, f"{file_path}{temp_file_suffix}", input_file, timeout) except OperationFailure: raise PyndowsException( f"Unable to write \\\\{connection.remote_name}\\{share_folder}{file_path}{temp_file_suffix}" ) if temp_file_suffix: try: connection.rename(share_folder, f"{file_path}{temp_file_suffix}", file_path) except OperationFailure: raise PyndowsException( f"Unable to rename temp file into \\\\{connection.remote_name}\\{share_folder}{file_path}" ) logger.info(f"File copied. Removing {input_file_path} file...") os.remove(input_file_path) logger.info( f"{input_file_path} file moved within \\\\{connection.remote_name}\\{share_folder}{file_path}." )
def _rename(connection: SMBConnection, share_folder: str, old_file_path: str, new_file_path: str): logger.info( f"Renaming \\\\{connection.remote_name}\\{share_folder}{old_file_path} " f"into \\\\{connection.remote_name}\\{share_folder}{new_file_path}...") try: connection.rename(share_folder, old_file_path, new_file_path) logger.info("File renamed...") except OperationFailure: raise Exception( f"Unable to rename \\\\{connection.remote_name}\\{share_folder}{old_file_path} " f"into \\\\{connection.remote_name}\\{share_folder}{new_file_path}" )
def _create_folder(connection: SMBConnection, share_folder: str, folder_path: str) -> bool: # Avoid trying to create an already existing folder if folder_path in ["", "/"] or get_file_desc(connection, share_folder, folder_path): return True try: # Create a temporary folder, then rename it for instant availability (Windows FS listeners for instance) connection.createDirectory(share_folder, f"{folder_path}temp") connection.rename(share_folder, f"{folder_path}temp", folder_path) return True except OperationFailure: # Silent failure as subsequent action will certainly fail anyway return False
class Nas: def __init__(self, config, connection): conf = config[connection] self.ip = conf['ip'] self.connection = SMBConnection(conf['user'], conf['password'], conf['local_name'], conf['nas_name']) self.connection.connect(self.ip) def set_root_directory(self, root): self.root = root def list_directory(self, path): return self.connection.listPath(self.root, path) def list_directory_names(self, path): dir_raw = self.list_directory(path) return [x.filename for x in dir_raw] def create_dir(self, path): self.connection.createDirectory(self.root, path) def download_file(self, origin, destination): with open(destination, 'wb') as download_file: # downloading file self.connection.retrieveFile(self.root, origin, download_file) def download_remote(self, path): filename = os.path.basename(path) file_obj = BytesIO() self.connection.retrieveFile(self.root, path, file_obj) return file_obj def upload_remote(self, path, file_obj): self.connection.storeFile(self.root, path, file_obj) def delete_file(self, path): self.connection.deleteFiles(self.root, path) def rename_path(self, origin, destination): self.connection.rename(origin, destination) def close(self): self.connection.close()
def print_photo(photo_file): """ printing a photo on a remote printer In this case we copy the file with smb to a remote windows server that monitors that share and prints the files """ conn = SMBConnection(SMB_USER, SMB_PW, CLIENT_NAME, SERVER_NAME, use_ntlm_v2=False) dest_file_name = os.path.basename(photo_file) tmp_file_name = dest_file_name + '.tmp' if conn.connect(SERVER_IP, 139): with open(photo_file, 'r') as fp: fp.seek(0) #first store in a temporary file to avoid that the print daemon starts with an incomplete file conn.storeFile(SMB_SHARE, tmp_file_name, fp) #rename to final file name conn.rename(SMB_SHARE, tmp_file_name, dest_file_name) conn.close() else: print('Cannot connect to server')
class SMB_client(): def __init__(self,username=None,password=None,smb_name=None,print_errors=True): self.username = username self.password = password self.smb_name = smb_name self.print_errors = print_errors self.smb_ip = None self.conn = None self.service_name = None self.my_name = None self.error = None self.tree = [] def getBIOSName(self, remote_smb_ip, timeout=5): # unused if dynamic IP # ip -> smb name try: self.error = None bios = NetBIOS() srv_name = bios.queryIPForName(remote_smb_ip, timeout=timeout) return srv_name[0] 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 getIP(self): # smb name -> ip try: self.error = None bios = NetBIOS() ip = bios.queryName(self.smb_name) return ip[0] 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 connect(self): try: self.error = None self.my_name = gethostname() # iDevice name self.smb_ip = self.getIP() smb_structs.SUPPORT_SMB2 = True self.conn = SMBConnection(self.username, self.password, self.my_name, self.smb_name, use_ntlm_v2 = True) self.conn.connect(self.smb_ip, 139) #139=NetBIOS / 445=TCP if self.conn: shares = self.conn.listShares() for share in shares: if share.type == 0: # 0 = DISK_TREE self.service_name = share.name 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 close(self): try: self.error = None self.conn.close() 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 getRemoteDir(self, path, pattern): try: self.error = None files = self.conn.listPath(self.service_name, path, pattern=pattern) return files 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 getRemoteTree(self,path=''): try: self.error = None if path == '': w = '' else: 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: filesize = self.conn.storeFile(self.service_name, path+filename, file_obj) break else: buffer_obj = file_obj.read(buffersize) if buffer_obj: buffer_fileobj = BytesIO() buffer_fileobj.write(buffer_obj) buffer_fileobj.seek(0) offset_new = self.conn.storeFileFromOffset(self.service_name, path+filename, buffer_fileobj, offset=offset, truncate=False) #return the file position where the next byte will be written. offset = offset_new if callback: callback(offset) else: break file_obj.close() #print('upload 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 delete_remote_file(self,path, filename): try: self.error = None self.conn.deleteFiles(self.service_name, path+filename) #print('Remotefile ' + path + filename + ' deleted') 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 createRemoteDir(self, path): try: self.error = None self.conn.createDirectory(self.service_name, path) 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 removeRemoteDir(self,path): try: self.error = None self.conn.deleteDirectory(self.service_name, path) 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 renameRemoteFileOrDir(self,old_path, new_path): try: self.error = None self.conn.rename(self.service_name, old_path, new_path) 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 rename(self,old_file_name,new_file_name):#重命名文件 old_file_name原文件名 new_file_name新文件名 conn = SMBConnection(self.username, self.password, self.my_name, self.remote_smb_IP, self.domain_name, use_ntlm_v2=True,is_direct_tcp = True) conn.connect(self.remote_smb_IP,445) conn.rename(self.dir, self.display_path + '/' + old_file_name, self.display_path + '/' + new_file_name)
class SMB_client(): def __init__(self, username=None, password=None, smb_name=None, print_errors=True): self.username = username self.password = password self.smb_name = smb_name self.print_errors = print_errors self.smb_ip = None self.conn = None self.service_name = None self.my_name = None self.error = None self.tree = [] def getBIOSName(self, remote_smb_ip, timeout=5): # unused if dynamic IP # ip -> smb name try: self.error = None bios = NetBIOS() srv_name = bios.queryIPForName(remote_smb_ip, timeout=timeout) return srv_name[0] 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 getIP(self): # smb name -> ip try: self.error = None bios = NetBIOS() ip = bios.queryName(self.smb_name) return ip[0] 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 connect(self): try: self.error = None self.my_name = gethostname() # iDevice name self.smb_ip = self.getIP() smb_structs.SUPPORT_SMB2 = True self.conn = SMBConnection(self.username, self.password, self.my_name, self.smb_name, use_ntlm_v2=True) self.conn.connect(self.smb_ip, 139) #139=NetBIOS / 445=TCP if self.conn: shares = self.conn.listShares() for share in shares: if share.type == 0: # 0 = DISK_TREE self.service_name = share.name 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 close(self): try: self.error = None self.conn.close() 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 getRemoteDir(self, path, pattern): try: self.error = None files = self.conn.listPath(self.service_name, path, pattern=pattern) return files 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 getRemoteTree(self, path=''): try: self.error = None if path == '': w = '' else: 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: filesize = self.conn.storeFile(self.service_name, path + filename, file_obj) break else: buffer_obj = file_obj.read(buffersize) if buffer_obj: buffer_fileobj = BytesIO() buffer_fileobj.write(buffer_obj) buffer_fileobj.seek(0) offset_new = self.conn.storeFileFromOffset( self.service_name, path + filename, buffer_fileobj, offset=offset, truncate=False) #return the file position where the next byte will be written. offset = offset_new if callback: callback(offset) else: break file_obj.close() #print('upload 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 delete_remote_file(self, path, filename): try: self.error = None self.conn.deleteFiles(self.service_name, path + filename) #print('Remotefile ' + path + filename + ' deleted') 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 createRemoteDir(self, path): try: self.error = None self.conn.createDirectory(self.service_name, path) 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 removeRemoteDir(self, path): try: self.error = None self.conn.deleteDirectory(self.service_name, path) 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 renameRemoteFileOrDir(self, old_path, new_path): try: self.error = None self.conn.rename(self.service_name, old_path, new_path) 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)