コード例 #1
0
ファイル: client_node.py プロジェクト: ihasn/fincrypt
	def rawDataReceived(self, data):
		filename = self.file_data[0]
		file_path = os.path.join(self.factory.files_path, filename)
		
		print 'Receiving file chunk (%d KB)' % (len(data))
		
		if not self.file_handler:
			self.file_handler = open(file_path, 'wb')
			
		if data.endswith('\r\n'):
			# Last chunk
			data = data[:-2]
			self.file_handler.write(data)
			self.setLineMode()
			
			self.file_handler.close()
			self.file_handler = None
			
			print 'gen hash:', get_file_md5_hash(file_path)
			print 'rcv hash:', self.file_data[1]
			
			if validate_file_md5_hash(file_path, self.file_data[1]):
				print 'File %s has been successfully transfered and saved' % (filename)
				try:
					self.factory.client.process_restore_folder()
				except AttributeError:
					return
			else:
				os.unlink(file_path)
				print 'File %s has been successfully transfered, but deleted due to invalid MD5 hash' % (filename)
			self.transport.loseConnection()
		else:
			self.file_handler.write(data)
コード例 #2
0
ファイル: client_node.py プロジェクト: ihasn/fincrypt
	def _send_file(self, file_path, filename):
		file_path = file_path + '/' + filename
		if not os.path.isfile(file_path):
			print "The file '%s' does not exist" % file_path
			return
		
		file_size = os.path.getsize(file_path) / 1024
		
		print 'Uploading file: %s (%d KB)' % (filename, file_size)
		
		md5_hash = get_file_md5_hash(file_path)
		signature = self.factory.rsa_key.sign(md5_hash, '')
		
		self.transport.write('PUT %s %s %s\n' % (filename, md5_hash, base64.b64encode(pickle.dumps(signature))))
		#self.setRawMode()
		for bytes in read_bytes_from_file(file_path):
			self.transport.write(bytes)
		
		self.transport.write('\r\n')  
		
		self.transport.loseConnection()
		
		#os.unlink(file_path) 
		
		# When the transfer is finished, we go back to the line mode 
		self.setLineMode()
コード例 #3
0
ファイル: client.py プロジェクト: tahyuu/paimai
    def _sendCommand(self, line):
        """ Sends a command to the server. """

        data = clean_and_split_input(line)
        if len(data) == 0 or data == '':
            return

        command = data[0].lower()
        if not command in COMMANDS:
            self._display_message('Invalid command')
            return

        if command == 'list' or command == 'help' or command == 'quit':
            self.connection.transport.write('%s\n' % (command))
        elif command == 'get':
            try:
                filename = data[1]
            except IndexError:
                self._display_message('Missing filename')
                return

            self.connection.transport.write('%s %s\n' % (command, filename))
        elif command == 'put':
            try:
                file_path = data[1]
                filename = data[2]
            except IndexError:
                self._display_message(
                    'Missing local file path or remote file name')
                return

            if not os.path.isfile(file_path):
                self._display_message('This file does not exist')
                return

            file_size = os.path.getsize(file_path) / 1024

            print 'Uploading file: %s (%d KB)' % (filename, file_size)

            self.connection.transport.write(
                'PUT %s %s\n' % (filename, get_file_md5_hash(file_path)))
            self.setRawMode()

            for bytes in read_bytes_from_file(file_path):
                self.connection.transport.write(bytes)

            self.connection.transport.write('\r\n')

            # When the transfer is finished, we go back to the line mode
            self.setLineMode()
        else:
            self.connection.transport.write('%s %s\n' % (command, data[1]))

        self.factory.deferred.addCallback(self._display_response)
コード例 #4
0
    def _sendCommand(self, line):
        """ Sends a command to the server. """
        
        data = clean_and_split_input(line) 
        if len(data) == 0 or data == '':
            return 

        command = data[0].lower()
        if not command in COMMANDS:
            self._display_message('Invalid command')
            return
        
        if command == 'list' or command == 'help' or command == 'quit':
            self.connection.transport.write('%s\n' % (command))
        elif command == 'get':
            try:
                filename = data[1]
            except IndexError:
                self._display_message('Missing filename')
                return
            
            self.connection.transport.write('%s %s\n' % (command, filename))
        elif command == 'put':
            try:
                file_path = data[1]
                filename = data[2]
            except IndexError:
                self._display_message('Missing local file path or remote file name')
                return
            
            if not os.path.isfile(file_path):
                self._display_message('This file does not exist')
                return

            file_size = os.path.getsize(file_path) / 1024
            
            print 'Uploading file: %s (%d KB)' % (filename, file_size)
            
            self.connection.transport.write('PUT %s %s\n' % (filename, get_file_md5_hash(file_path)))
            self.setRawMode()
            
            for bytes in read_bytes_from_file(file_path):
                self.connection.transport.write(bytes)
            
            self.connection.transport.write('\r\n')   
            
            # When the transfer is finished, we go back to the line mode 
            self.setLineMode()
        else:
            self.connection.transport.write('%s %s\n' % (command, data[1]))

        self.factory.deferred.addCallback(self._display_response)
コード例 #5
0
ファイル: magcli_1.py プロジェクト: imbang/magdc
    def dataReceived(self, data):
        "As soon as any data is received, write it back."
##        data = self._cleanAndSplitInput(data)
##        if data is None:
##            return
        
        if data is None or len(data) == 0 or data == '':
	    return
        data = data.strip()
##        if data=='.':
##            print '.'
##            return
        
##        print data
        if data.endswith('auth'):
            dt = data.split('\n')
            dt = dt[0].split(' ')
            print '%s %s %s %s %s' % (dt[0],dt[1],dt[2],dt[3],dt[4])
            print "sending authentification..."
            self.transport.write('auth %s %s %s %d\n' % (self.factory.user,self.factory.psw,self.factory.ipaddr,self.factory.staid))
        elif data.endswith('file'):
            try:
                file_path = self.factory.filename
                filename = self.factory.filename
            except IndexError:
                print 'Missing local file path or remote file name'
                return
            
            if not os.path.isfile(file_path):
                print 'This file does not exist'
                return

            file_size = os.path.getsize(file_path) / 1024
            
            print 'Uploading file: %s (%d KB)' % (filename, file_size)
            
            self.transport.write('PUT %s %s\n' % (os.path.basename(filename), get_file_md5_hash(file_path)))
            self.setRawMode()
            
            for bytes in read_bytes_from_file(file_path):
                self.transport.write(bytes)
            
            self.transport.write('\r\n')   
            
            # When the transfer is finished, we go back to the line mode 
            self.setLineMode()
        elif data.endswith('put-ok'):
            print "successfully transfered..."
            self.isTransferOK = True
        elif data.endswith('put-fail'):
            print "File transfer is fail..."
コード例 #6
0
ファイル: magsrv_twis.py プロジェクト: imbang/magdc
	def _get_file_list(self):
		""" Returns a list of the files in the specified directory as a dictionary:
		
		dict['file name'] = (file path, file size, file md5 hash)
		"""
		
		file_list = {}
		for filename in os.listdir(self.factory.files_path):
			file_path = os.path.join(self.factory.files_path, filename)
			
			if os.path.isdir(file_path):
				continue
			
			file_size = os.path.getsize(file_path)
			md5_hash = get_file_md5_hash(file_path)

			file_list[filename] = (file_path, file_size, md5_hash)

		return file_list
コード例 #7
0
ファイル: server.py プロジェクト: adamxu0220/SCT
	def _get_file_list(self):
		""" Returns a list of the files in the specified directory as a dictionary:
		
		dict['file name'] = (file path, file size, file md5 hash)
		"""
		
		file_list = {}
		for filename in os.listdir(self.factory.files_path):
			file_path = os.path.join(self.factory.files_path, filename)
			
			if os.path.isdir(file_path):
				continue
			
			file_size = os.path.getsize(file_path)
			md5_hash = get_file_md5_hash(file_path)

			file_list[filename] = (file_path, file_size, md5_hash)

		return file_list
コード例 #8
0
ファイル: client_protocol.py プロジェクト: adamxu0220/SCT
    def __upload_file(self, line):
        """ Download a file from the server. """
        data = clean_and_split_input(line)
        if len(data) == 0 or data == '' or self.transport == None:
            return False
        command = data[0].lower()
        if command == 'upload':
            try:
                file_path = data[1]
                filename = data[2]
                cmdid = data[3]
                result = data[4]
            except IndexError:
                self._display_message(
                    'Missing local file path or remote file name')
                return False

            if not os.path.isfile(file_path):
                self._display_message('This file does not exist')
                return False

            file_size = os.path.getsize(file_path) / 1024
            self.prv_logger.trace('Uploading file: %s (%d KB)' %
                                  (filename, file_size))
            self.transport.write(
                'upload %s %s %s %s\n' %
                (filename, get_file_md5_hash(self.prv_logger,
                                             file_path), cmdid, result))
            self.setRawMode()

            for bytes in read_bytes_from_file(file_path):
                self.transport.write(bytes)

            self.transport.write('\r\r\r\r\n')

            # When the transfer is finished, we go back to the line mode
            self.setLineMode()
            return True
        else:
            self.prv_logger.error("invalid cmd:%s" % command)
            return False
コード例 #9
0
    def _sendCommand(self, line):
	global setSynchronize, synchronized
        """ Sends a command to the server. """

        data = clean_and_split_input(line)
        if len(data) == 0 or data == '':
            return
	
	command = data[0].lower()

        if not command in COMMANDS:
            self._display_message('Invalid command')
            return

        '''TLast
        if command == 'list' or command == 'help' or command == 'quit':
            self.connection.transport.write('%s %s\n' % (command, self.username))
        '''

	if command == 'help':
	    if self.logged_in == False:
		self._display_message('Type login [username] [password] to login OR type register [username] [password] [user/admin] to register')
		return
            self.connection.transport.write('%s %s\n' % (command, self.username))

	elif command == 'list':
	    if self.logged_in == False:
		self._display_message('You must be logged in')
		return
            self.connection.transport.write('%s %s\n' % (command, self.username))
	
	elif command == 'registry':
	    if self.logged_in == False:
		self._display_message('You must be logged in')
		return
            self.connection.transport.write('%s %s\n' % (command, self.username))

	elif command == 'register':
	    if self.logged_in == True:
		self._display_message('You must log out to register a new user')
		return
	    try:
		username = data[1]
		password = data[2]
		role = data[3]
		
	    except IndexError:
                self._display_message('Missing username or password')
		return

            self.connection.transport.write('%s %s %s %s %s\n' % (command, username, password, role, self.username))
	
	elif command == 'change_password':
	    if self.logged_in == False:
		self._display_message('You must be logged in')
		return
	    try:
	        username = data[1]
  		password = data[2]

	    except IndexError:
                self._display_message('Missing username or password')
		return
            self.connection.transport.write('%s %s %s %s\n' % (command, username, password, self.username))

	elif command == 'remove_user':
	    if self.logged_in == False:
		self._display_message('You must be logged in')
		return
	    try:
	        username = data[1]
	    except IndexError:
                self._display_message('Missing username')
		return
            self.connection.transport.write('%s %s %s\n' % (command, username, self.username))

	elif command == 'login':
	    if self.logged_in != False:
		self._display_message('You are already logged in. Log out to change users.')
		return
	    try:
		username = data[1]
		password = data[2]
	    except IndexError:
                self._display_message('Missing username or password')
		return
            self.connection.transport.write('%s %s %s %s\n' % (command, username, password, self.username))

	elif command == 'logout':
	    if self.logged_in != True:
		self._display_message('You are not logged into any account.')
		return
            self.connection.transport.write('%s %s\n' % (command, self.username))

#############################
        elif command == 'get':
	    if self.logged_in == False:
		self._display_message('You must be logged in')
		return
            try:
                filename = data[1]
            except IndexError:
                self._display_message('Missing filename')
                return
            
            self.connection.transport.write('%s %s %s\n' % (command, filename, self.username))

#############################
        elif command == 'put':

	    if self.logged_in == False:
		self._display_message('You must be logged in')
		return
            try:
                file_path = data[1]
                filename = data[2]
            except IndexError:
                self._display_message('Missing local file path or remote file name')
                return
            
            if not os.path.isfile(file_path):
                self._display_message('This file does not exist')
                return

            file_size = os.path.getsize(file_path) / 1024
            
            print 'Uploading file: %s (%d KB)' % (filename, file_size)
            
            self.connection.transport.write('PUT %s %s %s\n' % (filename, get_file_md5_hash(file_path), self.username))
            self.setRawMode()
            
            for bytes in read_bytes_from_file(file_path):
                self.connection.transport.write(bytes)
            
            self.connection.transport.write('\r\n')   
            
            # When the transfer is finished, we go back to the line mode 
            self.setLineMode()

#####################################
        elif command == 'rename':
            """renames file or directory src to dst and returns True if successful"""
	    if self.logged_in == False:
		self._display_message('You must be logged in.')
	        self._prompt()
            else:
                src = '';
                dst = '';
                input = clean_and_split_input(line)
                if len(input) == 3:
                    src = input[1];
                    dst = input[2];
                if os.path.isfile(src) or os.path.isdir(src):
                    try:
                        os.renames(src, dst)
                        print '%s renamed to %s' % (src, dst)
                        self._prompt()
                    except OSError, e:
                        print e
                        self._prompt()
                else:
                    print "%s does not exist" % src
                    self._prompt()
コード例 #10
0
    def sendNotification(self):
        global fileActivity, path, dest,username, synchronized, setSynchronize, client_username
        fileList = []
        if setSynchronize and (not synchronized):
            print("Start synchronization")
            #clear the previous file activity detected by watchdog
            fileActivity = []
            #deleting the old oneDir and creating new oneDir
            print("Deleting previously stored oneDir on server")

            src = dest + username + '/OneDir'

            #have to replace ' ' with '|' to prevent ' ' error
            src_new = src.replace(' ','|')

            (self.server)[0].transport.write('DELETE %s %s %s\n' % (src_new, 0, client_username))

            #for directory
            (self.server)[0].transport.write('PUTDIR %s %s %s\n' % (src_new, 0, client_username))


            # When the transfer is finished, we go back to the line mode
            (self.server)[0].setLineMode()


            #upload onedir
            for root, subFolders, files in os.walk(path):
                for f in subFolders:
                    fileList.append(os.path.join(root,f))
                for file in files:
                    fileList.append(os.path.join(root,file))
            print fileList

            #upload the files
            for f in fileList:
                fileActivity.append("Upload" + "|" + (trimPath(f))[1])

            #start synchronize
            synchronized = True

        if (not setSynchronize) and synchronized:
            print("Stop synchronization")
            synchronized = False
        if synchronized:
            if(len(fileActivity) != 0):
                # (self.server)[0].transport.write(fileActivity[0]+"\n")

                #manage fileActivity
                f1 = fileActivity[0].strip().split("|")
                if(f1[0] == "Delete"):
                    print("Deleting " + f1[1])

                    src = dest + username + '/OneDir/' + f1[1]

                    #have to replace ' ' with '|' to prevent ' ' error
                    src_new = src.replace(' ','|')

                    (self.server)[0].transport.write('DELETE %s %s %s\n' % (src_new, 0, client_username))

                    # When the transfer is finished, we go back to the line mode
                    (self.server)[0].setLineMode()

                elif(f1[0] == "Upload"):
                    #uploading
                    print("Uploading " + path + f1[1])
                    file_path = path + f1[1]
                    filename = dest + username + '/OneDir/' +f1[1]
                    isDir = 0
                    ############# testing #############
                    print("current filename is " + filename)
                    print("file to append is : " + f1[1])
                    if os.path.isdir(file_path):
                        isDir = 1
                    elif os.path.isfile(file_path):
                        isDir = 0
                    else:
                        print "%s does not exist" % file_path
                        return

                    #calculate file size
                    file_size = os.path.getsize(file_path) / 1024

                    #have to replace ' ' with '|' to prevent ' ' error
                    filename_new = filename.replace(' ','|')

                    if( not isDir):
                        (self.server)[0].transport.write('PUT %s %s %s\n' % (filename_new, get_file_md5_hash(file_path), client_username))
                        (self.server)[0].setRawMode()

                        for bytes in read_bytes_from_file(file_path):
                            (self.server)[0].transport.write(bytes)


                        (self.server)[0].transport.write('\r\n') #the end of raw input
                    else:
                        #for directory
                        (self.server)[0].transport.write('PUTDIR %s %s %s\n' % (filename_new, 0, client_username))

                    # When the transfer is finished, we go back to the line mode
                    (self.server)[0].setLineMode()

                #remove activity from the queue
                del fileActivity[0]
コード例 #11
0
ファイル: storage_node.py プロジェクト: ihasn/fincrypt
	def lineReceived(self, line):
		#display_message('Received the following line from the client [%s]: %s' % (self.transport.getPeer().host, line))
		
		data = self._cleanAndSplitInput(line)
		if len(data) == 0 or data == '':
			return 
		
		command = data[0].lower()
		print command
		if not command in COMMANDS:
			self.transport.write('Invalid command\n')
			self.transport.write('ENDMSG\n')
			return
		if command == 'list':
			self._send_list_of_files()
		elif command == 'get':
			try:
				filename = data[1]
			except IndexError:
				self.transport.write('Missing filename\n')
				self.transport.write('ENDMSG\n')
				return
			
			if not self.factory.files:
				self.factory.files = self._get_file_list()
				
			if not filename in self.factory.files:
				self.transport.write('File with filename %s does not exist\n' % (filename))
				self.transport.write('ENDMSG\n')
				return
			
			display_message('Sending file: %s (%d KB)' % (filename, self.factory.files[filename][1] / 1024))
			
			self.transport.write('HASH %s %s\n' % (filename, get_file_md5_hash(self.factory.files_path + '/' + filename)))
			self.setRawMode()
			
			for bytes in read_bytes_from_file(os.path.join(self.factory.files_path, filename)):
				self.transport.write(bytes)
			
			self.transport.write('\r\n')	
			self.setLineMode()
		elif command == 'put':
			try:
				filename = data[1]
				file_hash = data[2]
				signed_hash = pickle.loads(base64.b64decode(data[3]))
			except IndexError:
				self.transport.write('Missing filename or file MD5 hash\n')
				self.transport.write('ENDMSG\n')
				return
			
			self.file_data = (filename, file_hash, signed_hash)
			
			# Switch to the raw mode (for receiving binary data)
			print 'Receiving file: %s' % (filename)
			self.setRawMode()
		elif command == 'help':
			self.transport.write('Available commands:\n\n')
			
			for key, value in COMMANDS.iteritems():
				self.transport.write('%s - %s\n' % (value[0], value[1]))
			
			self.transport.write('ENDMSG\n')				
		elif command == 'quit':
			self.transport.loseConnection()
コード例 #12
0
ファイル: onedir3_client.py プロジェクト: dwd4bc/Team3_repo
    def _sendCommand(self, line):
        """ Sends a command to the server. """
        
        data = clean_and_split_input(line) 
        if len(data) == 0 or data == '':
            return 

        command = data[0].lower()
        if not command in COMMANDS:
            self._display_message('Invalid command')
            return
        
        if command == 'list' or command == 'help' or command == 'quit':
            self.connection.transport.write('%s\n' % (command))

	elif command == 'register':
	    try:
		username = data[1]
		password = data[2]
	    except IndexError:
                self._display_message('Missing username or password')
		return
            self.connection.transport.write('%s %s %s\n' % (command, username, password))

	elif command == 'login':
	    try:
		username = data[1]
		password = data[2]
	    except IndexError:
                self._display_message('Missing username or password')
		return
            self.connection.transport.write('%s %s %s\n' % (command, username, password))

        elif command == 'get':
            try:
                filename = data[1]
            except IndexError:
                self._display_message('Missing filename')
                return
            
            self.connection.transport.write('%s %s\n' % (command, filename))
        elif command == 'put':
            try:
                file_path = data[1]
                filename = data[2]
            except IndexError:
                self._display_message('Missing local file path or remote file name')
                return
            
            if not os.path.isfile(file_path):
                self._display_message('This file does not exist')
                return

            file_size = os.path.getsize(file_path) / 1024
            
            print 'Uploading file: %s (%d KB)' % (filename, file_size)
            
            self.connection.transport.write('PUT %s %s\n' % (filename, get_file_md5_hash(file_path)))
            self.setRawMode()
            
            for bytes in read_bytes_from_file(file_path):
                self.connection.transport.write(bytes)
            
            self.connection.transport.write('\r\n')   
            
            # When the transfer is finished, we go back to the line mode 
            self.setLineMode()
        elif command == 'rename':
            """renames file or directory src to dst and returns True if successful"""
            src = '';
            dst = '';
            input = clean_and_split_input(line)
            if len(input) == 3:
                src = input[1];
                dst = input[2];
            if os.path.isfile(src) or os.path.isdir(src):
                try:
                    os.renames(src,dst)
                    return True
		except OSError, e:
                    print e
                    return False
            else: 
		print "%s does not exist" % src
		return False
コード例 #13
0
ファイル: client.py プロジェクト: ananya1122/SharePy
    def _sendCommand(self, line):
        """ Sends a command to the server. """
        
       
        data = clean_and_split_input(line) 
        if len(data) == 0 or data == '':
            return 

        command = data[0].lower()
        
        
		
        if not ((command in COMMANDS ) or(command in RESPONSE ) ):
            self._display_message('Invalid command')
            return
        
        if command == 'list' or command == 'help' or command == "people" or command == 'quit':
            
            self.connection.transport.write('%s\n' % (command))
        
        elif command == 'get':
            try:
                filename = data[1]
            except IndexError:
                self._display_message('Missing filename')
                return
            
            self.connection.transport.write('%s %s\n' % (command, filename))
        elif command == 'put':
            try:
                file_path = data[1]
                filename = data[2]
            except IndexError:
                self._display_message('Missing local file path or remote file name')
                return
            
            if not os.path.isfile(file_path):
                self._display_message('This file does not exist')
                return

            file_size = os.path.getsize(file_path) / 1024
            
            print 'Uploading file: %s (%d KB)' % (filename, file_size)
            
            self.connection.transport.write('PUT %s %s\n' % (filename, get_file_md5_hash(file_path)))
            self.setRawMode()
            
            for bytes in read_bytes_from_file(file_path):
                self.connection.transport.write(bytes)
            
            self.connection.transport.write('\r\n')   
            
            # When the transfer is finished, we go back to the line mode 
            self.setLineMode()
        
		
        elif command == 'sync' :
            files = []
            files = [ f for f in os.listdir(self.files_path) if os.path.isfile(os.path.join(self.files_path,f)) ]
            file_list = '#'.join(files)
            self.connection.transport.write('sync %s\n' % (file_list))
        
        elif command == 'nick' :
            try:
                subcommand = data[1]
                nick = data[2]
                passw = data[3]
            except IndexError:
                self._display_message('Missing subcommand {and\or} nick {and\or} password')
                return
				
            self.connection.transport.write('nick %s %s %s\n' % (subcommand, nick,passw))
			
        elif command == 'recv' :
            self.connection.transport.write('%s %s\n' % (command , data[1]))
        
        else:
            self.connection.transport.write('%s %s\n' % (command, data[1]))

        self.factory.deferred.addCallback(self._display_response)
        self.factory.deferred1.addCallback(self._display_response)
コード例 #14
0
    def _sendCommand(self, line):
        """ Sends a command to the server. """

        data = clean_and_split_input(line)
        if len(data) == 0 or data == '':
            return

        command = data[0].lower()

        if not ((command in COMMANDS) or (command in RESPONSE)):
            self._display_message('Invalid command')
            return

        if command == 'list' or command == 'help' or command == "people" or command == 'quit':

            self.sender.transport.write('%s\n' % (command))

        if command == 'finger':
            try:
                nickname = data[1]
            except IndexError:
                self._display_message('Missing nickname')
                return

            self.sender.transport.write('%s %s\n' % (command, nickname))

        elif command == 'get':
            try:
                filename = data[1]
            except IndexError:
                self._display_message('Missing filename')
                return

            self.sender.transport.write('%s %s\n' % (command, filename))
        elif command == 'put':
            try:
                file_path = data[1]
                filename = data[2]
            except IndexError:
                self._display_message(
                    'Missing local file path or remote file name')
                return

            if not os.path.isfile(file_path):
                self._display_message('This file does not exist')
                return

            file_size = os.path.getsize(file_path) / 1024

            print('Uploading file: %s (%d KB)' % (filename, file_size))

            self.sender.transport.write(
                'PUT %s %s\n' % (filename, get_file_md5_hash(file_path)))
            self.sender.setRawMode()

            for bytes in read_bytes_from_file(file_path):
                self.sender.transport.write(bytes)

            self.sender.transport.write('\r\n')

            # When the transfer is finished, we go back to the line mode
            self.sender.setLineMode()

        elif command == 'sync':
            files = []
            files = [
                f for f in os.listdir(self.sender.factory.files_path)
                if os.path.isfile(
                    os.path.join(self.sender.factory.files_path, f))
            ]
            file_list = '#'.join(files)
            self.sender.transport.write('sync %s\n' % (file_list))

        elif command == 'search':
            try:
                filename = data[1]
            except IndexError:
                self._display_message('Missing filename')
                return

            if os.path.exists(
                    os.path.join(self.sender.factory.files_path, filename)):
                self._display_message(
                    'File already exists on your local folder')
                return

            self.sender.transport.write('search %s\n' % (filename))

        elif command == 'nick':
            try:
                subcommand = data[1]
                nick = data[2]
                passw = data[3]
            except IndexError:
                self._display_message(
                    'Missing subcommand {and\or} nick {and\or} password')
                return

            self.sender.transport.write('nick %s %s %s\n' %
                                        (subcommand, nick, passw))

        elif command == 'recv':
            self.sender.transport.write('%s %s\n' % (command, data[1]))
コード例 #15
0
                #uploading
                print("Uploading " + path + f1[1])
                file_path = path + f1[1]
                filename = dest + f1[1]

                if not os.path.isfile(file_path):
                    print('ERROR: path does not exist')
                    return

                #calculate file size
                file_size = os.path.getsize(file_path) / 1024

                #have to replace ' ' with '|' to prevent ' ' error
                filename_new = filename.replace(' ','|')

                (self.server)[0].transport.write('PUT %s %s\n' % (filename_new, get_file_md5_hash(file_path)))
                (self.server)[0].setRawMode()

                for bytes in read_bytes_from_file(file_path):
                    (self.server)[0].transport.write(bytes)


                (self.server)[0].transport.write('\r\n')

                # When the transfer is finished, we go back to the line mode
                (self.server)[0].setLineMode()

            del fileActivity[0]

    def serverConnectionMade(self, server):
        self.server.append(server)
コード例 #16
0
ファイル: client_protocol.py プロジェクト: adamxu0220/SCT
    def _sendCommand(self, line):
        """ Sends a command to the server. """

        data = clean_and_split_input(line)
        if len(data) == 0 or data == '' or self.transport == None:
            return

        command = data[0].lower()
        if not command in COMMANDS:
            self._display_message('Invalid command:%s' % command)
            return

        if command == 'list' or command == 'help' or command == 'quit':
            self.transport.write('%s\n' % (command))
        elif command == 'get':
            try:
                src_filename = data[1]
                dst_filename = data[2]
            except IndexError:
                self._display_message('Missing filename')
                return

            self.transport.write('%s %s %s\n' %
                                 (command, src_filename, dst_filename))
        elif command == 'put':
            try:
                file_path = data[1]
                filename = data[2]
            except IndexError:
                self._display_message(
                    'Missing local file path or remote file name')
                return

            if not os.path.isfile(file_path):
                self._display_message('This file does not exist')
                return

            file_size = os.path.getsize(file_path) / 1024

            self.prv_logger.trace('Uploading file: %s (%d KB)' %
                                  (filename, file_size))

            self.transport.write(
                'PUT %s %s\n' %
                (filename, get_file_md5_hash(self.prv_logger, file_path)))
            self.setRawMode()

            for bytes in read_bytes_from_file(file_path):
                self.transport.write(bytes)

            self.transport.write('\r\r\r\r\n')

            # When the transfer is finished, we go back to the line mode
            self.setLineMode()
        elif command == 'download':
            try:
                src_filename = data[1]
                dst_filename = data[2]
            except IndexError:
                self._display_message('Missing filename')
                return
            self.prv_logger.trace('%s %s %s\n' %
                                  ("get", src_filename, dst_filename))
            self.transport.write('%s %s %s\n' %
                                 ("get", src_filename, dst_filename))
            self.prv_logger.trace('%s %s %s done\n' %
                                  ("get", src_filename, dst_filename))
        elif command == 'hb':
            self.transport.write('%s %s\n' % (command, ' '.join(data[1:])))
        else:
            self.transport.write('%s %s\n' % (command, data[1]))
コード例 #17
0
    def lineReceived(self, line):
        display_message(
            self.prv_logger,
            'Received the following line from the client [%s]: %s' %
            (self.transport.getPeer().host, line))

        data = self._cleanAndSplitInput(line)
        if len(data) == 0 or data == '':
            return

        command = data[0].lower()
        if not command in COMMANDS:
            self.transport.write('Invalid command:%s\n' % command)
            self.transport.write('ENDMSG\n')
            return
        if command == 'list':
            self._send_list_of_files()
        elif command == 'get':
            try:
                src_filename = data[1]
                dst_filename = data[2]
            except IndexError:
                self.transport.write('Missing filename\n')
                self.transport.write('ENDMSG\n')
                return
            abs_file_path = os.path.join(self.factory.files_path, src_filename)
            if not os.path.isfile(abs_file_path):
                self.transport.write('File with filename %s does not exist\n' %
                                     (src_filename))
                self.transport.write('ENDMSG\n')
                return
            file_size = os.path.getsize(abs_file_path)
            md5_hash = get_file_md5_hash(abs_file_path)

            display_message(
                self.prv_logger, 'Sending file to (%s:%s): %s (%d KB)' %
                (str(self.transport.getPeer().host),
                 str(self.transport.getPeer().port), src_filename,
                 file_size / 1024))

            self.transport.write('HASH %s %s\n' % (dst_filename, md5_hash))
            self.setRawMode()

            for bytes in read_bytes_from_file(abs_file_path):
                self.transport.write(bytes)

            self.transport.write('\r\r\r\r\n')
            self.setLineMode()
        elif command == 'put' or command == 'upload':
            try:
                filename = data[1]
                file_hash = data[2]
            except IndexError:
                self.transport.write('Missing filename or file MD5 hash\n')
                self.transport.write('ENDMSG\n')
                return
            if command == 'upload':
                try:
                    id = data[3]
                    result = data[4]
                except IndexError:
                    self.transport.write('Missing id or result when upload\n')
                    self.transport.write('ENDMSG\n')
                    return
                timeStamp = time.strftime("%Y-%m-%d %H:%M:%S",
                                          time.localtime())
                if not update_special_cmd(self.mysql_hdlr, id, {
                        'status': 'finished',
                        'end_time': timeStamp,
                        'result': result
                }):
                    self.prv_logger.error(
                        "update mysql failed; status: running->finished")
                self.file_data["%s:%s" %
                               (str(self.transport.getPeer().host),
                                str(self.transport.getPeer().port))] = {
                                    'filename': filename,
                                    'file_hash': file_hash,
                                    'id': id
                                }
            else:
                self.file_data["%s:%s" %
                               (str(self.transport.getPeer().host),
                                str(self.transport.getPeer().port))] = {
                                    'filename': filename,
                                    'file_hash': file_hash
                                }

            # Switch to the raw mode (for receiving binary data)
            print 'Receiving file: %s' % (filename)
            self.setRawMode()
        elif command == 'case_finished':
            id = data[1]
            result = data[2]
            timeStamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            self.prv_logger.trace("update mysql, case id:%s, result:%s" %
                                  (id, result))
            if len(data) > 3:
                if not update_special_cmd(
                        self.mysql_hdlr, id, {
                            'status': 'finished',
                            'end_time': timeStamp,
                            'result': result,
                            'reserved': ' '.join(data[3:])
                        }):
                    self.prv_logger.error(
                        "update mysql failed; status: running->finished")
            elif not update_special_cmd(self.mysql_hdlr, id, {
                    'status': 'finished',
                    'end_time': timeStamp,
                    'result': result
            }):
                self.prv_logger.error(
                    "update mysql failed; status: running->finished")
            self.transport.write('ENDMSG\n')
        elif command == 'help':
            self.transport.write('Available commands:\n\n')

            for key, value in COMMANDS.iteritems():
                self.transport.write('%s - %s\n' % (value[0], value[1]))

            self.transport.write('ENDMSG\n')
        elif command == 'hb':
            try:
                owner = data[1]
                hostname = data[2].lower()
                macaddr = data[3].lower()
                duttype = data[4]
                dutip = data[5]
                swversion = data[6]
                status = data[7]
                taskid = data[8]
                timeStamp = time.strftime("%Y-%m-%d %H:%M:%S",
                                          time.localtime())
                update_connection_cmd(
                    self.mysql_hdlr, {
                        'end_time': timeStamp,
                        'status': 'offline',
                        'client_pcname': hostname
                    }, {'mac_addr': macaddr},
                    where_str_addtional='client_conn_port != %s' %
                    str(self.transport.getPeer().port))
                update_connection_cmd(
                    self.mysql_hdlr, {
                        'mac_addr': macaddr,
                        'owner': owner,
                        'dut_type': duttype,
                        'dut_ip': dutip,
                        'sw_version': swversion,
                        'status': status,
                        'client_pcname': hostname
                    }, {
                        'client_conn_port': str(self.transport.getPeer().port),
                        'client_ip': str(self.transport.getPeer().host)
                    },
                    where_str_addtional='order by id desc limit 1')
                update_connection_id(self.mysql_hdlr, {'mac_addr': macaddr})
                conn_info = get_connection_info(
                    self.mysql_hdlr, {
                        'client_conn_port': str(self.transport.getPeer().port),
                        'client_ip': str(self.transport.getPeer().host)
                    })
                if conn_info != None:
                    client_id = conn_info['client_id']
                else:
                    client_id = 0
                #hardcode
                self.prv_logger.trace("current connection id:%d" % client_id)
                private_cmd = get_private_cmd(self.mysql_hdlr, owner, duttype,
                                              client_id, swversion)
                neighbour_cmd = get_neighbour_cmd(self.mysql_hdlr, owner,
                                                  duttype, client_id,
                                                  swversion)
                if status == 'idle':
                    self.busy_cnt = 0
                    #self.transport.write('start_testcase %s\n'%os.path.join("BG2CDP", "Chromecast_HBOGO.tar.gz"))
                    if private_cmd != None: cmd_list = private_cmd
                    elif neighbour_cmd != None: cmd_list = neighbour_cmd
                    else:
                        self.prv_logger.trace(
                            "could not get any command from mysql")
                        cmd_list = None

                    if cmd_list != None:
                        case_info = get_case_info(self.mysql_hdlr,
                                                  {'id': cmd_list['case_id']})
                        if case_info != None:
                            start_case_cmd = case_info['path']
                        else:
                            start_case_cmd
                    else:
                        start_case_cmd = None
                    if start_case_cmd != None:
                        self.transport.write(
                            'start_testcase %s %s %s %s\n' %
                            (start_case_cmd,
                             os.path.join("TestCase", "Config",
                                          str(cmd_list['id']), 'config.py'),
                             cmd_list['id'], cmd_list['case_parametar']))
                        timeStamp = time.strftime("%Y-%m-%d %H:%M:%S",
                                                  time.localtime())
                        if not update_special_cmd(
                                self.mysql_hdlr, cmd_list['id'], {
                                    'status': 'running',
                                    'exc_client_id': client_id,
                                    'start_time': timeStamp,
                                    'sw_version': swversion
                                }):
                            self.prv_logger.error(
                                "update mysql failed;status:not run->running")
                    #self.transport.write('ENDMSG\n')
                elif status == 'busy':
                    #update_special_cmd(self.mysql_hdlr, taskid, {'status':'running', 'sw_version':swversion})
                    self.prv_logger.trace("dut is busy(id:%s)" % taskid)
                    res = get_special_cmd(self.mysql_hdlr, taskid)
                    if res != None:
                        if res['status'] == 'running':
                            self.prv_logger.trace('got it(id:%s)' % taskid)
                            if res['cmd_owner'] != owner and private_cmd != None:
                                self.prv_logger.trace(
                                    'case(id:%s; case_id:%s; owner:%s) will be canceled;'
                                    % (res['id'], res['case_id'],
                                       res['cmd_owner']))
                                self.prv_logger.trace(
                                    'case(id:%s; case_id:%s; owner:%s) will be run;'
                                    %
                                    (private_cmd['id'], private_cmd['case_id'],
                                     private_cmd['cmd_owner']))
                                if not update_special_cmd(
                                        self.mysql_hdlr, taskid,
                                    {'status': 'not run'}):
                                    self.prv_logger.error(
                                        "update mysql failed;status:not running->not run"
                                    )
                                self.transport.write('cancel_testcase\n')
                                update_special_cmd(self.mysql_hdlr, taskid, {
                                    'status': 'not run',
                                    'sw_version': swversion
                                })
                        elif res['status'] == 'stopped':
                            self.transport.write('stop_testcase\n')
                            update_special_cmd(
                                self.mysql_hdlr, taskid, {
                                    'status': 'finished',
                                    'result': 'stopped',
                                    'reserved': 'manually stopped',
                                    'sw_version': swversion
                                })
                        elif res['status'] == 'restart':
                            self.transport.write('cancel_testcase\n')
                            update_special_cmd(
                                self.mysql_hdlr, taskid, {
                                    'status': 'not run',
                                    'reserved': 'manually canceled',
                                    'sw_version': swversion
                                })
                        else:
                            update_special_cmd(self.mysql_hdlr, taskid, {
                                'status': 'running',
                                'sw_version': swversion
                            })
                            self.prv_logger.trace('invalid status:%s (id:%s)' %
                                                  (res['status'], taskid))
                    else:
                        self.prv_logger.error('could not get(id:%s) in db' %
                                              taskid)

                else:
                    """
                                    should be hang or other unhandle status,
                                    need notify administrator and client owner
                                    """
                self.transport.write('ENDMSG\n')
                print "owner:%s hostname:%s macaddr:%s duttype:%s dutip:%s swversion:%s status:%s" % (
                    owner, hostname, macaddr, duttype, dutip, swversion,
                    status)
            except IndexError:
                self.transport.write(
                    'Missing hostname, macaddr, duttype or swversion\n')
                self.transport.write('ENDMSG\n')
                self.prv_logger.trace(
                    'Missing hostname, macaddr, duttype or swversion\n')
                return

#except Exception, e:
#        self.prv_logger.trace('Capture exception:%s'%str(e))
#except:
#        self.prv_logger.trace('Capture unknown exception')
        elif command == 'quit':
            self.transport.loseConnection()