当前位置: 首页>>代码示例>>Python>>正文


Python SMBConnection.storeFile方法代码示例

本文整理汇总了Python中smb.SMBConnection.SMBConnection.storeFile方法的典型用法代码示例。如果您正苦于以下问题:Python SMBConnection.storeFile方法的具体用法?Python SMBConnection.storeFile怎么用?Python SMBConnection.storeFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在smb.SMBConnection.SMBConnection的用法示例。


在下文中一共展示了SMBConnection.storeFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: SmbClient

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import storeFile [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
开发者ID:rahulinux,项目名称:PythonPractice-,代码行数:32,代码来源:samba_client.py

示例2: _transfer_file_on_nas

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import storeFile [as 别名]
    def _transfer_file_on_nas(self, file_name):
        """
        Puts the letter file on the NAS folder for the translation platform.
        :return: None
        """
        self.ensure_one()
        # 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):
            raise Exception('No config SMB in file .conf')

        # Copy file in the imported letter folder
        smb_conn = SMBConnection(smb_user, smb_pass, 'openerp', 'nas')
        if smb_conn.connect(smb_ip, smb_port):
            file_ = BytesIO(base64.b64decode(
                self.letter_image.with_context(
                    bin_size=False).datas))
            nas_share_name = self.env.ref(
                'sbc_translation.nas_share_name').value

            nas_letters_store_path = self.env.ref(
                'sbc_translation.nas_letters_store_path').value + file_name
            smb_conn.storeFile(nas_share_name,
                               nas_letters_store_path, file_)

            logger.info('File {} store on NAS with success'
                        .format(self.letter_image.name))
        else:
            raise Warning(_('Connection to NAS failed'))
开发者ID:MickSandoz,项目名称:compassion-switzerland,代码行数:34,代码来源:correspondence.py

示例3: SambaHelper

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import storeFile [as 别名]
class SambaHelper():
    def __init__(self, user, password, serverName):
        self.__username = user
        self.__password = password
        self.__connect(serverName)

    def __connect(self, serverName):
        self.conn = SMBConnection(self.__username, self.__password, '','',use_ntlm_v2 = True)
        self.conn.connect(serverName, 139)
        print "Connected."

    def CopyFileToSambaShare(self, fileName, shareName):
        file_obj=file(fileName, 'r')
        print file_obj.name
        self.conn.storeFile(shareName, '/{0}'.format(fileName), file_obj)
    
    def CopyFilesToSambaShare(self, inputDir, shareName):
        files = os.listdir(inputDir)
        for file in files:
            if file.endswith('.jpg'):
                print file
                self.CopyFileTo("{0}/{1}".format(inputDir,file), shareName)

    def CloseConnection():
        self.conn.close()
开发者ID:oaicstef,项目名称:RaspPhotoBooth,代码行数:27,代码来源:connectToSambaShare.py

示例4: notify_smb

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import storeFile [as 别名]
def notify_smb(isn, timestamp, msg):
	server_name = ""
	client_machine_name = "Onegin"
	server_ip = "172.18.212.211"
	userID = "szsfis"
	password = "szsfis"
	conn = SMBConnection(userID, password, client_machine_name, server_name, use_ntlm_v2 = True)
	assert conn.connect(server_ip, 139)
	filename = "%s_%s.csv" % (isn, timestamp)
	conn.storeFile("sz_sfis_event_log", filename, StringIO.StringIO(msg))
开发者ID:fragileness,项目名称:importer,代码行数:12,代码来源:mla_processmining_consumer.py

示例5: FileServerConnection

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import storeFile [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)
开发者ID:reskontr,项目名称:nephy,代码行数:49,代码来源:auth.py

示例6: uploadCmdrWatch

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import storeFile [as 别名]
def uploadCmdrWatch(barcodeFile, dataType, data, config):
    try:
        localslug = re.sub('[^\w-]+', '_', barcodeFile).strip().lower()
        barcodeFh = codecs.open('/tmp/%s' % localslug, 'w', 'utf-8-sig')
        csvlogfh = csv.writer(barcodeFh, delimiter=",", quoting=csv.QUOTE_ALL)
        if dataType == 'locationLabels':
            csvlogfh.writerow('termdisplayname'.split(','))
            for d in data:
                csvlogfh.writerow((d[0],))  # writerow needs a tuple or array
        elif dataType == 'objectLabels':
            csvlogfh.writerow(
                'MuseumNumber,ObjectName,PieceCount,FieldCollectionPlace,AssociatedCulture,EthnographicFileCode'.split(
                    ','))
            for d in data:
                csvlogfh.writerow(d[3:9])
        barcodeFh.close()
    except:
        # raise
        barcodeFile = '<span style="color:red;">could not write to /tmp/%s</span>' % localslug
        return barcodeFile

    try:

        # OK, now we have the file object with the data in it. write it to the
        # commanderWatch server via SMB

        domain = config.get('files', 'domain')
        userID = config.get('files', 'userID')
        password = config.get('files', 'password')
        client_name = config.get('files', 'client_name')
        server_ip = config.get('files', 'server_ip')
        service_name = config.get('files', 'service_name')

        # client_machine_name can be an arbitary ASCII string
        # server_name should match the remote machine name, or else the connection will be rejected
        #
        # SMBConnection(username, password, my_name, remote_name, domain='')
        conn = SMBConnection(userID, password, client_name, service_name, domain, is_direct_tcp=True)
        assert conn.connect(server_ip, 445)

        # storeFile(service_name, path, file_obj, timeout=30)
        # service_name - the name of the shared folder for the path

        barcodeFh = open('/tmp/%s' % localslug, 'rb')
        bytes = conn.storeFile(service_name, barcodeFile, barcodeFh)

        barcodeFh.close()
        os.unlink('/tmp/%s' % localslug)
        return barcodeFile
    except:
        # raise
        os.unlink('/tmp/%s' % localslug)
        barcodeFile = '<span style="color:red;">could not transmit %s to commanderWatch</span>' % barcodeFile
        return barcodeFile
开发者ID:chrshffmn,项目名称:Tools,代码行数:56,代码来源:cswaSMBclient.py

示例7: attach_pictures

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import storeFile [as 别名]
    def attach_pictures(self, cr, uid, ids, pictures_id, context=None):
        """ Push the new picture. """
        res = super(child_property, self).attach_pictures(
            cr, uid, ids, pictures_id, context)

        pictures = self.pool.get('compassion.child.pictures').browse(
            cr, uid, pictures_id, context)

        # 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):
            raise orm.except_orm(
                'Config Error',
                'Missing Samba configuration in conf file.')
        child = pictures.child_id

        date_pic = pictures.date.replace('-', '')
        gp_pic_path = "{0}{1}/".format(config.get('gp_pictures'),
                                       child.code[:2])
        file_name = "{0}_{1}.jpg".format(child.code, date_pic)
        picture_file = TemporaryFile()
        picture_file.write(base64.b64decode(pictures.fullshot))
        picture_file.flush()
        picture_file.seek(0)

        # Upload file to shared folder
        smb_conn = SMBConnection(smb_user, smb_pass, 'openerp', 'nas')
        if smb_conn.connect(smb_ip, smb_port):
            try:
                smb_conn.storeFile(
                    'GP', gp_pic_path + file_name, picture_file)
            except OperationFailure:
                # Directory may not exist
                smb_conn.createDirectory('GP', gp_pic_path)
                smb_conn.storeFile(
                    'GP', gp_pic_path + file_name, picture_file)
        return res
开发者ID:steveferry,项目名称:compassion-switzerland,代码行数:42,代码来源:child.py

示例8: check_ip

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import storeFile [as 别名]
def check_ip(ip):
    global timeout, verbose, user, password, domain, print_lock, debug

    try:
        # Connect to socket
        conn = SMBConnection(user, password, "detect_unsecure_admin_share.py", ip, domain=domain, use_ntlm_v2=True, is_direct_tcp=True)
        assert conn.connect(ip, 445, timeout=timeout)
        if debug:
            with print_lock:
                print("#DEBUG: Successfully connected to ip: {}".format(ip))
        
        f = tempfile.TemporaryFile()
        f.write("Hello World!\n")
        
        try:
            conn.storeFile("C$", "detect_unsecure_admin_share.tmp", f, timeout=timeout)
            with print_lock:
                print("#SUCCESS: Successfully stored test file on C$ admin share at ip: {}".format(ip))
        
            conn.deleteFiles("C$", "detect_unsecure_admin_share.tmp", timeout=timeout)
            if debug:
                with print_lock:
                    print("#DEBUG: Successfully deleted test file from C$ admin share at ip: {}".format(ip))
        except Exception as ex:
            if debug:
                with print_lock:
                    print("#ERROR: Could not store file on C$ admin share on ip: {}".format(ip))
        finally:
            conn.close()
            f.close()
    
    except socket.timeout:
        if debug:
            with print_lock:
                print("#DEBUG: Connection timed out for ip: {}".format(ip))
    except Exception as ex:
        if debug:
            with print_lock:
                print("#DEBUG: Connection failure for ip: {}".format(ip))
开发者ID:bananabr,项目名称:netadmin_scripts,代码行数:41,代码来源:detect_unsecure_admin_share.py

示例9: __init__

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import storeFile [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)
开发者ID:G-Goldstein,项目名称:Python-Config-Auditor,代码行数:40,代码来源:connector.py

示例10: SMB_client

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import storeFile [as 别名]

#.........这里部分代码省略.........
			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)
开发者ID:cvpe,项目名称:Pythonista-scripts,代码行数:104,代码来源:SMB_client.py

示例11: smb_open

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import storeFile [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]
开发者ID:Element-s,项目名称:pysmb,代码行数:72,代码来源:SMBHandler.py

示例12: SMB_Connect

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import storeFile [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()
开发者ID:abuzze,项目名称:check_smb.py,代码行数:67,代码来源:check_smb.py

示例13: CommonCIFSShare

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import storeFile [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
开发者ID:MediaKraken,项目名称:MediaKraken_Deployment,代码行数:98,代码来源:common_network_cifs.py

示例14: handle_JobMessage

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import storeFile [as 别名]
    def handle_JobMessage(self, msg):
        try:
            self.errors = ""

            def set_status(s):
                self.status = s
                self.log.info(s)

            set_status("Received job")
            sim = msg.get_property("msg")

            user_id = sim["user_id"]
            sim_id = sim["sim_id"]
            job_id = sim["job_id"]
            sample = sim["sample"]
            jar_hash = sim["jar_hash"]

            set_status("Starting job %d %d %s %d" % (job_id, sim_id, user_id, sample))
            self.send_status("Starting job", job_id, sim_id, user_id, sample)

            out_name = os.path.join("results", self.worker_id)
            jar_name = os.path.join("jars", "%s_%s.run" % (jar_hash, self.worker_id))
            xml_name = os.path.join("xmls", "%s_%i_%i_%i.xml" % (user_id, job_id, sim_id, sample))

            set_status("Writing input files")
            self.send_status("Writing input files", job_id, sim_id, user_id, sample)

            xml = construct_xml(sim, out_name)
            if not xml:
                self.errors = "Error constructing XML (check idrefs?)"
                set_status(self.errors)
                raise Exception(self.errors)

            with open(xml_name, "w") as xml_file:
                xml_file.write(xml)

            if not os.path.exists(jar_name):
                with open(jar_name, "wb") as jar_file:
                    jar_file.write(get_file(jar_hash))

            process = Popen(["java", "-server", "-Xmx2400M", "-jar", jar_name, xml_name], stdout=PIPE, stderr=PIPE)
            p_timer = time.time()

            # Non-blocking process io: http://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python
            def enqueue_output(stream, queue, running):
                while running.value:
                    queue.put(stream.read(128))

            def create_thread_queue(stream, running):
                q = Queue()
                t = Thread(target=enqueue_output, args=(stream, q, running))
                t.daemon = True
                t.start()
                return q

            running = Value("b", True)
            out_q = create_thread_queue(process.stdout, running)
            err_q = create_thread_queue(process.stderr, running)

            set_status("Execution started")
            while process.poll() == None:
                try:
                    status = out_q.get(timeout=0.1)

                    if time.time() - p_timer > 0.3:
                        s = re.findall("\(.*?\)", status)[-1]
                        self.send_status(s, job_id, sim_id, user_id, sample)

                        p_timer = time.time()
                except:
                    pass

            # Stop the queue threads
            running.value = False

            # Get the error if it exists, only needed here because thread is constantly checking the pipe
            while not err_q.empty():
                self.errors += err_q.get(False)

            os.remove(xml_name)
            set_status("Execution finished")

            if self.errors:
                set_status(self.errors)
                raise Exception("CIlib error")

            set_status("Posting results")
            with open(out_name, "r") as result_file:
                conn = SMBConnection(SMB_USER, SMB_PWD, "", "", use_ntlm_v2=True)
                assert conn.connect(SMB_IP, timeout=SMB_TIMEOUT)

                newFile = "%s_%i_%i_%i.txt" % (user_id, job_id, sim_id, sample)
                existingFiles = [i.filename for i in conn.listPath(SMB_SHARE, "/")]

                if newFile in existingFiles:
                    conn.deleteFiles(SMB_SHARE, newFile, timeout=SMB_TIMEOUT)

                conn.storeFile(SMB_SHARE, newFile, result_file, timeout=SMB_TIMEOUT)
                conn.close()

#.........这里部分代码省略.........
开发者ID:kidaak,项目名称:pleiades-3,代码行数:103,代码来源:worker.py

示例15: smb_open

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import storeFile [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])
开发者ID:50onRed,项目名称:pysmb,代码行数:64,代码来源:SMBHandler.py


注:本文中的smb.SMBConnection.SMBConnection.storeFile方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。