Пример #1
0
    def next(self):
        """ Returns the next completion suggestion """
        if len(self.completion_list) > 0:
            program, args = parser(self.completion_buffer)
            if 'target' in args and args['target'] != '.':
                args['target'] = escape(self.completionPath + self.completion_list[self.completion_index])
            else:
                args['path'][-1] = escape(self.completion_list[self.completion_index])
            buffer = assemble(program, args)
        else:
            buffer = self.completion_buffer

        # Increment completion index
        self.completion_index += 1
        if self.completion_index >= len(self.completion_list):
            self.completion_index = 0

        return buffer
Пример #2
0
    def next(self):
        """ Returns the next completion suggestion """
        if len(self.completion_list) > 0:
            program, args = parser(self.completion_buffer)
            if 'target' in args and args['target'] != '.':
                args['target'] = escape(
                    self.completionPath +
                    self.completion_list[self.completion_index])
            else:
                args['path'][-1] = escape(
                    self.completion_list[self.completion_index])
            buffer = assemble(program, args)
        else:
            buffer = self.completion_buffer

        # Increment completion index
        self.completion_index += 1
        if self.completion_index >= len(self.completion_list):
            self.completion_index = 0

        return buffer
Пример #3
0
    def complete(self, buffer):
        """ Actual function called by the terminal.

        Creates a list of possible completions and returns the first element
        """

        # Save buffer for later completions
        self.completion_buffer = buffer

        # In case the parser fails, we don't want any error messages or crashes
        # The error message will be displayed, if he presses enter
        try:
            program, args = parser(buffer)
        except ArgumentParseException:
            return buffer

        if 'path' in args:
            self.completion_index = 0

            if program == 'push':
                # Local completion
                if 'target' in args and args['target'] != '.':
                    self.remote_completion_list(args['target'])

                # Remote completion
                else:
                    self.local_completion_list(unescape(args['path'])[-1])
            else:
                # Local completion
                if 'target' in args and args['target'] != '.':
                    self.local_completion_list(args['target'])

                # Remote completion
                else:
                    self.remote_completion_list(unescape(args['path'])[-1])

            return self.next()
        else:
            self.completion_list = []
            return self.completion_buffer
Пример #4
0
    def complete(self, buffer):
        """ Actual function called by the terminal.

        Creates a list of possible completions and returns the first element
        """

        # Save buffer for later completions
        self.completion_buffer = buffer

        # In case the parser fails, we don't want any error messages or crashes
        # The error message will be displayed, if he presses enter
        try:
            program, args = parser(buffer)
        except ArgumentParseException:
            return buffer

        if "path" in args:
            self.completion_index = 0

            if program == "push":
                # Local completion
                if "target" in args and args["target"] != ".":
                    self.remote_completion_list(args["target"])

                # Remote completion
                else:
                    self.local_completion_list(unescape(args["path"])[-1])
            else:
                # Local completion
                if "target" in args and args["target"] != ".":
                    self.local_completion_list(args["target"])

                # Remote completion
                else:
                    self.remote_completion_list(unescape(args["path"])[-1])

            return self.next()
        else:
            self.completion_list = []
            return self.completion_buffer
Пример #5
0
    def complete(self, buffer):
        """ Actual function called by the terminal. Creates a list of possible completions and returns the first element """

        # Save buffer for later completions
        self.completion_buffer = buffer

        program, args = parser(buffer)
        if 'path' in args:
            self.completion_index = 0

            # Local completion
            if 'target' in args and args['target'] != '.':
                self.local_completion_list(args['target'])

            # Remote completion
            else:
                self.remote_completion_list(unescape(args['path'])[-1])

            return self.next()
        else:
            self.completion_list = []
            return self.completion_buffer
Пример #6
0
    def complete(self, buffer):
        """ Actual function called by the terminal. Creates a list of possible completions and returns the first element """

        # Save buffer for later completions
        self.completion_buffer = buffer

        program, args = parser(buffer)
        if 'path' in args:
            self.completion_index = 0

            # Local completion
            if 'target' in args and args['target'] != '.':
                self.local_completion_list(args['target'])

            # Remote completion
            else:
                self.remote_completion_list(unescape(args['path'])[-1])

            return self.next()
        else:
            self.completion_list = []
            return self.completion_buffer
Пример #7
0
def main():
    arrrsync_args = vars(server_parser.parse_args(sys.argv))
    command = os.environ.get('SSH_ORIGINAL_COMMAND')
    program, args = parser(command)
    if program is None:
        print('Invalid Command. Supported Programs: \nls \ncd \nisdir \nrsync')
    if program == 'ls':
        ls_args = ['ls']
        # Args for ls
        if args['a']:
            ls_args.append('-a')
        if args['l']:
            ls_args.append('-l')
        if args['h']:
            ls_args.append('-h')
        if args['path']:
            for item in args['path']:
                targetDir = get_target_dir(arrrsync_args['path'],
                                           unescape(item))
                ls_args.append(targetDir)

        # Creating new subprocess for ls, read the output and print it
        process = subprocess.Popen(ls_args,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        stdout, stderr = process.communicate()
        print_response(stdout, stderr)

    elif program == 'cd':
        # Args for cd
        if args['path']:
            target = args['path'][0]
            targetDir = get_target_dir(arrrsync_args['path'], unescape(target))
            if os.path.isdir(targetDir):
                print(targetDir)
            else:
                print("'{}' is not a directory".format(args['path']),
                      file=sys.stderr)

    elif program == 'isdir':
        # Args for cd
        if args['path']:
            target = args['path'][0]
            targetDir = get_target_dir(arrrsync_args['path'], unescape(target))
            if os.path.isdir(targetDir):
                print('True')
            else:
                print('False')
        print("False")

    elif program == 'rsync':
        # Compile rsync arguments
        rsync_args = ['rsync']
        if args['server']:
            rsync_args.append('--server')

        if args['recursive']:
            rsync_args.append('--recursive')
        if args['partial']:
            rsync_args.append('--partial')
        if args['perms']:
            rsync_args.append('--perms')
        if args['times']:
            rsync_args.append('--times')

        if args['one_file_system']:
            rsync_args.append('--one-file-system')
        if args['cvs_exclude']:
            rsync_args.append('--cvs-exclude')
        if args['ignore_times']:
            rsync_args.append('--ignore-times')

        # Don't allow users to copy symlinked directories.
        rsync_args.append('--links')
        rsync_args.append('--info=progress2')

        # Sender flag is set. This means the server will send some data
        if args['sender']:
            if arrrsync_args['r'] is not True:
                print("Reading is not allowed for your key. Aborting")
                sys.exit(0)

            rsync_args.append('--sender')
            for path in args['path']:
                if not path == '.':
                    path = get_target_dir(arrrsync_args['path'],
                                          unescape(path))
                rsync_args.append(path)
        # Sender flag isn't set. This means the server will receive some data
        else:
            if arrrsync_args['w'] is not True:
                print("Writing is not allowed for your key. Aborting")
                sys.exit(0)
            path = args['path'][-1]
            if not path == '.':
                path = get_target_dir(arrrsync_args['path'], unescape(path))
            rsync_args.append(path)

        rsync_process = subprocess.Popen(rsync_args, shell=False)
        rsync_process.communicate()

    sys.exit(0)
Пример #8
0
def main():
    arrrsync_args = vars(server_parser.parse_args(sys.argv))
    command = os.environ.get('SSH_ORIGINAL_COMMAND')
    program, args = parser(command)
    if program is None:
        print('Invalid Command. Supported Programs: \nls \ncd \nisdir \nrsync')
    if program == 'ls':
        ls_args = ['ls']
        # Args for ls
        if args['a']:
            ls_args.append('-a')
        if args['l']:
            ls_args.append('-l')
        if args['h']:
            ls_args.append('-h')
        if args['path']:
            for item in args['path']:
                targetDir = get_target_dir(arrrsync_args['path'], unescape(item))
                ls_args.append(targetDir)

        # Creating new subprocess for ls, read the output and print it
        process = subprocess.Popen(ls_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = process.communicate()
        print_response(stdout, stderr)

    elif program == 'cd':
        # Args for cd
        if args['path']:
            target = args['path'][0]
            targetDir = get_target_dir(arrrsync_args['path'], unescape(target))
            if os.path.isdir(targetDir):
                print(targetDir)
            else:
                print("'{}' is not a directory".format(args['path']), file=sys.stderr)

    elif program == 'isdir':
        # Args for cd
        if args['path']:
            target = args['path'][0]
            targetDir = get_target_dir(arrrsync_args['path'], unescape(target))
            if os.path.isdir(targetDir):
                print('True')
            else:
                print('False')
        print("False")

    elif program == 'rsync':
        # Compile rsync arguments
        rsync_args = ['rsync']
        if args['server']:
            rsync_args.append('--server')

        if args['recursive']:
            rsync_args.append('--recursive')
        if args['partial']:
            rsync_args.append('--partial')
        if args['perms']:
            rsync_args.append('--perms')
        if args['times']:
            rsync_args.append('--times')

        if args['one_file_system']:
            rsync_args.append('--one-file-system')
        if args['cvs_exclude']:
            rsync_args.append('--cvs-exclude')
        if args['ignore_times']:
            rsync_args.append('--ignore-times')

        # Don't allow users to copy symlinked directories.
        rsync_args.append('--links')
        rsync_args.append('--info=progress2')

        # Sender flag is set. This means the server will send some data
        if args['sender']:
            if arrrsync_args['r'] is not True:
                print("Reading is not for your key allowed. Aborting")
                sys.exit(0)

            rsync_args.append('--sender')
            for path in args['path']:
                if not path == '.':
                    path = get_target_dir(arrrsync_args['path'], unescape(path))
                rsync_args.append(path)
        # Sender flag isn't set. This means the server will receive some data
        else:
            if arrrsync_args['w'] is not True:
                print("Writing is not for your key allowed. Aborting")
                sys.exit(0)
            path = args['path'][-1]
            if not path == '.':
                path = get_target_dir(arrrsync_args['path'], unescape(path))
            rsync_args.append(path)


        rsync_process = subprocess.Popen(rsync_args, shell=False)
        rsync_process.communicate()

    sys.exit(0)
Пример #9
0
    def interpret(self, command):
        command = command.lstrip()
        # Parsing input, getting actual command name and arguments
        try:
            program, args = parser(command)
        except ArgumentParserError as error:
            self.terminal.add_lines(format_parse_error(error, command))
            return True

        if program == 'ls':
            compiled_paths = map(
                lambda path: os.path.join(self.current_path, path),
                args['path'])
            args['path'] = list(compiled_paths)
            # Send command to server
            stdin, stdout, stderr = self.client.exec_command(ls_assemble(args))

            # Print response
            for line in stdout.readlines():
                self.terminal.add_line(line.rstrip('\n'))

        elif program == 'cd':
            # Compute path
            targetPath = os.path.join(self.current_path, args['path'][0])
            args['path'] = [targetPath]

            # Send command to server
            stdin, stdout, stderr = self.client.exec_command(cd_assemble(args))

            errors = []
            for line in stderr.readlines():
                errors.append(line.rstrip('\n'))

            if not len(errors) > 1:
                # Save current position
                self.current_path = escape(stdout.readline().rstrip('\n'))
            else:
                # Print response
                self.terminal.add_lines(errors)

        elif program == 'push':
            rsync_args = ['rsync']
            rsync_args.append('--recursive')
            rsync_args.append('--partial')
            rsync_args.append('--perms')
            rsync_args.append('--times')
            rsync_args.append('--links')
            rsync_args.append('--info=progress2')

            rsync_args += args['files']

            target_path = '{}:{}'.format(
                self.rsync[0], os.path.join(self.current_path, args['target']))
            rsync_args.append(target_path)

            rsync_process = subprocess.Popen(rsync_args,
                                             stdout=subprocess.PIPE,
                                             stderr=subprocess.STDOUT)
            # Add a line in the terminal self.lines. We need this for update_last_lines to work
            self.terminal.add_line('')
            # Continously pass output to terminal, abort rsync process if ctrl-c occurs
            try:
                no_error = True
                while rsync_process.poll() is None and no_error:
                    line = rsync_process.stdout.readline()
                    line = line.rstrip()
                    line = line.decode('utf-8')

                    if line != '':
                        self.terminal.update_last_lines([line])
                    no_error = rsync_error_check(line)
                stdout, stderr = rsync_process.communicate()
            except KeyboardInterrupt:
                self.terminal.add_line(
                    'Terminating rsync process, please wait')
                rsync_process.terminate()
                rsync_process.communicate()
                self.terminal.update_last_lines(['Rsync process terminated'])

        elif program == 'get':
            rsync_args = ['rsync']
            # rsync_args.append("-e 'ssh -p {}'".format(self.rsync[1]))
            rsync_args.append('--recursive')
            rsync_args.append('--partial')
            rsync_args.append('--perms')
            rsync_args.append('--times')
            rsync_args.append('--links')
            rsync_args.append('--info=progress2')

            compiled_paths = map(
                lambda path: '{}:{}'.format(
                    self.rsync[0], os.path.join(self.current_path, path)),
                args['path'])
            rsync_args += list(compiled_paths)

            rsync_args.append(os.path.expanduser(args['target']))

            rsync_process = subprocess.Popen(rsync_args,
                                             stdout=subprocess.PIPE,
                                             stderr=subprocess.STDOUT)
            # Add a line in the terminal self.lines. We need this for update_last_lines to work
            self.terminal.add_line('')
            # Continously pass output to terminal, abort rsync process if ctrl-c occurs
            try:
                no_error = True
                while rsync_process.poll() is None and no_error:
                    line = rsync_process.stdout.readline()
                    line = line.rstrip()
                    line = line.decode('utf-8')

                    if line != '':
                        self.terminal.update_last_lines([line])
                    no_error = rsync_error_check(line)
                stdout, stderr = rsync_process.communicate()
            except KeyboardInterrupt:
                self.terminal.add_line(
                    'Terminating rsync process, please wait')
                rsync_process.terminate()
                rsync_process.communicate()
                self.terminal.update_last_lines(['Rsync process terminated'])

        elif program == 'exit':
            return False
        else:
            self.terminal.add_line('Invalid Command. Valid Commands are:')
            self.terminal.add_line(
                'ls [path], cd [path], get [-r] [path], exit')

        return True
Пример #10
0
    def interpret(self, command):
        command = command.lstrip()
        # Parsing input, getting actual command name and arguments
        try:
            program, args = parser(command)
        except ArgumentParserError as error:
            self.terminal.add_lines(format_parse_error(error, command))
            return True

        if program == 'ls':
            compiled_paths = map(lambda path: os.path.join(self.current_path, path), args['path'])
            args['path'] = list(compiled_paths)
            # Send command to server
            stdin, stdout, stderr = self.client.exec_command(ls_assemble(args))

            # Print response
            for line in stdout.readlines():
                self.terminal.add_line(line.rstrip('\n'))

        elif program == 'cd':
            # Compute path
            targetPath = os.path.join(self.current_path, args['path'][0])
            args['path'] = [targetPath]

            # Send command to server
            stdin, stdout, stderr = self.client.exec_command(cd_assemble(args))

            errors = []
            for line in stderr.readlines():
                errors.append(line.rstrip('\n'))

            if not len(errors) > 1:
                # Save current position
                self.current_path = escape(stdout.readline().rstrip('\n'))
            else:
                # Print response
                self.terminal.add_lines(errors)

        elif program == 'push':
            rsync_args = ['rsync']
            rsync_args.append('--recursive')
            rsync_args.append('--partial')
            rsync_args.append('--perms')
            rsync_args.append('--times')
            rsync_args.append('--links')
            rsync_args.append('--info=progress2')

            rsync_args += args['files']

            target_path = '{}:{}'.format(self.rsync[0], os.path.join(self.current_path, args['target']))
            rsync_args.append(target_path)

            rsync_process = subprocess.Popen(rsync_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            # Add a line in the terminal self.lines. We need this for update_last_lines to work
            self.terminal.add_line('')
            # Continously pass output to terminal, abort rsync process if ctrl-c occurs
            try:
                no_error = True
                while rsync_process.poll() is None and no_error:
                    line = rsync_process.stdout.readline()
                    line = line.rstrip()
                    line = line.decode('utf-8')

                    if line != '':
                        self.terminal.update_last_lines([line])
                    no_error = rsync_error_check(line)
                stdout, stderr = rsync_process.communicate()
            except KeyboardInterrupt:
                self.terminal.add_line('Terminating rsync process, please wait')
                rsync_process.terminate()
                rsync_process.communicate()
                self.terminal.update_last_lines(['Rsync process terminated'])

        elif program == 'get':
            rsync_args = ['rsync']
            # rsync_args.append("-e 'ssh -p {}'".format(self.rsync[1]))
            rsync_args.append('--recursive')
            rsync_args.append('--partial')
            rsync_args.append('--perms')
            rsync_args.append('--times')
            rsync_args.append('--links')
            rsync_args.append('--info=progress2')

            compiled_paths = map(lambda path: '{}:{}'.format(self.rsync[0], os.path.join(self.current_path, path)), args['path'])
            rsync_args += list(compiled_paths)

            rsync_args.append(os.path.expanduser(args['target']))

            rsync_process = subprocess.Popen(rsync_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            # Add a line in the terminal self.lines. We need this for update_last_lines to work
            self.terminal.add_line('')
            # Continously pass output to terminal, abort rsync process if ctrl-c occurs
            try:
                no_error = True
                while rsync_process.poll() is None and no_error:
                    line = rsync_process.stdout.readline()
                    line = line.rstrip()
                    line = line.decode('utf-8')

                    if line != '':
                        self.terminal.update_last_lines([line])
                    no_error = rsync_error_check(line)
                stdout, stderr = rsync_process.communicate()
            except KeyboardInterrupt:
                self.terminal.add_line('Terminating rsync process, please wait')
                rsync_process.terminate()
                rsync_process.communicate()
                self.terminal.update_last_lines(['Rsync process terminated'])

        elif program == 'exit':
            return False
        else:
            self.terminal.add_line('Invalid Command. Valid Commands are:')
            self.terminal.add_line('ls [path], cd [path], get [-r] [path], exit')

        return True