Exemple #1
0
    def __init__(self, host, user_id, password=None, key_file=None):
        self.user_id = user_id
        self.transport = paramiko.Transport(sock="{}:{}".format(host, 22))
        sshuser = SshUser.objects.filter(username_id=user_id).first()
        self.username = sshuser.username.username

        passwd = sshuser.password
        if passwd:
            password = base64.b64decode(passwd).decode('utf-8')
        else:
            password = None
        if sshuser.is_key:
            string_io = StringIO()
            string_io.write(sshuser.ssh_key)
            string_io.flush()
            string_io.seek(0)
            ssh_key = string_io
            key = get_key_obj(paramiko.RSAKey, pkey_obj=ssh_key, password=password) or \
                  get_key_obj(paramiko.DSSKey, pkey_obj=ssh_key, password=password) or \
                  get_key_obj(paramiko.ECDSAKey, pkey_obj=ssh_key, password=password) or \
                  get_key_obj(paramiko.Ed25519Key, pkey_obj=ssh_key, password=password)

            self.transport.connect(username=self.username, pkey=key)
        else:
            self.transport.connect(username=self.username, password=password)

        self.sftp = paramiko.SFTPClient.from_transport(self.transport)
Exemple #2
0
def reload_task_data(request):
    from django.utils.six import StringIO

    commands = [
        'update_tasks_git',
        'loadtasks',
        'collectqueststatic'
    ]

    results = []

    for command in commands:
        try:
            stdout = StringIO()
            stderr = StringIO()
            call_command(command, stdout=stdout, stderr=stderr)
        except CommandError as e:
            stderr.write('\n\nCommand failed cause {}'.format(e))

        results.append({
            'command': command,
            'stdout': stdout.getvalue(),
            'stderr': stderr.getvalue()
        })

    return render(request, 'quests/command_results.html', {
        'title': 'Update tasks',
        'commands': results,
    })
Exemple #3
0
    def connect(self):
        try:
            self.accept()
            query_string = self.scope['query_string']
            connet_argv = QueryDict(query_string=query_string,
                                    encoding='utf-8')
            unique = connet_argv.get('unique')
            width = connet_argv.get('width')
            height = connet_argv.get('height')

            width = int(width)
            height = int(height)

            connect_info = models.HostTmp.objects.get(unique=unique)

            host = connect_info.host
            port = connect_info.port
            user = connect_info.user
            auth = connect_info.auth
            pwd = connect_info.password
            pkey = connect_info.pkey

            connect_info.delete()

            if pwd:
                password = base64.b64decode(pwd).decode('utf-8')
            else:
                password = None

            self.ssh = SSH(websocker=self, message=self.message)

            if auth == 'key':
                pkey = pkey
                obj = StringIO()
                obj.write(pkey)
                obj.flush()
                obj.seek(0)
                self.pkey = obj

                self.ssh.connect(host=host,
                                 user=user,
                                 password=password,
                                 pkey=self.pkey,
                                 port=port,
                                 pty_width=width,
                                 pty_height=height)
            else:
                self.ssh.connect(host=host,
                                 user=user,
                                 password=password,
                                 port=port,
                                 pty_width=width,
                                 pty_height=height)
        except Exception as e:
            self.message['status'] = 1
            self.message['message'] = str(e)
            message = json.dumps(self.message)
            self.send(message)
            self.close()
Exemple #4
0
    def connect(self):
        """
        打开 websocket 连接, 通过前端传入的参数尝试连接 ssh 主机
        :return:
        """
        self.accept()
        query_string = self.scope.get('query_string')
        ssh_args = QueryDict(query_string=query_string, encoding='utf-8')

        width = ssh_args.get('width')
        height = ssh_args.get('height')
        port = ssh_args.get('port')

        width = int(width)
        height = int(height)
        port = int(port)

        auth = ssh_args.get('auth')
        ssh_key_name = ssh_args.get('ssh_key')
        passwd = ssh_args.get('password')

        host = ssh_args.get('host')
        user = ssh_args.get('user')

        if passwd:
            passwd = base64.b64decode(passwd).decode('utf-8')
        else:
            passwd = None

        self.ssh = SSH(websocker=self, message=self.message)

        ssh_connect_dict = {
            'host': host,
            'user': user,
            'port': port,
            'timeout': 30,
            'pty_width': width,
            'pty_height': height,
            'password': passwd
        }

        if auth == 'key':
            # ssh_key_file = os.path.join(settings.MEDIA_ROOT, ssh_key_name)
            # with open(ssh_key_file, 'r') as f:
            #     ssh_key = f.read()
            #从数据库获取秘钥信息
            ssh_key = SshUser.objects.filter(username=user).values_list(
                'ssh_key', flat=True)[0]
            string_io = StringIO()
            string_io.write(ssh_key)
            string_io.flush()
            string_io.seek(0)
            ssh_connect_dict['ssh_key'] = string_io

            # os.remove(ssh_key_file)

        self.ssh.connect(**ssh_connect_dict)
Exemple #5
0
    def connect(self):
        """
        打开 websocket 连接, 通过前端传入的参数尝试连接 ssh 主机
        :return:
        """
        self.accept()
        query_string = self.scope.get('query_string')
        ssh_args = QueryDict(query_string=query_string, encoding='utf-8')

        width = ssh_args.get('width')
        height = ssh_args.get('height')
        port = ssh_args.get('port')

        width = int(width)
        height = int(height)
        port = int(port)

        auth = ssh_args.get('auth')
        ssh_key_name = ssh_args.get('ssh_key')
        passwd = ssh_args.get('password')

        host = ssh_args.get('host')
        user = ssh_args.get('user')
        terminal_id = ssh_args.get("terminal_id")

        if passwd:
            passwd = base64.b64decode(passwd).decode('utf-8')
        else:
            passwd = None
        self.ssh = SSH(websocker=self, message=self.message)

        ssh_connect_dict = {
            'host': host,
            'user': user,
            'port': port,
            'timeout': 30,
            'pty_width': width,
            'pty_height': height,
            'password': passwd,
            'terminal_id': terminal_id
        }

        if auth == 'key':
            ssh_key_file = os.path.join(TMP_DIR, ssh_key_name)
            with open(ssh_key_file, 'r') as f:
                ssh_key = f.read()

            string_io = StringIO()
            string_io.write(ssh_key)
            string_io.flush()
            string_io.seek(0)
            ssh_connect_dict['ssh_key'] = string_io

            os.remove(ssh_key_file)

        self.ssh.connect(**ssh_connect_dict)
Exemple #6
0
    def test_stringio(self):
        # Test passing StringIO instance as content argument to save
        output = StringIO()
        output.write('content')
        output.seek(0)

        # Save it and read written file
        temp_storage.save('tests/stringio', output)
        self.assertTrue(temp_storage.exists('tests/stringio'))
        with temp_storage.open('tests/stringio') as f:
            self.assertEqual(f.read(), b'content')
Exemple #7
0
    def test_stringio(self):
        # Test passing StringIO instance as content argument to save
        output = StringIO()
        output.write('content')
        output.seek(0)

        # Save it and read written file
        temp_storage.save('tests/stringio', output)
        self.assertTrue(temp_storage.exists('tests/stringio'))
        with temp_storage.open('tests/stringio') as f:
            self.assertEqual(f.read(), b'content')
    def test_get_method_returns_csv_of_data_as_content(self):
        request = test.RequestFactory().get("/")
        sut = SampleCSVResponse()
        sut.field_names = ["first_field", "second_field"]
        response = sut.get(request)

        s = StringIO()
        for i in response.streaming_content:
            s.write(i.decode("utf-8"))

        self.assertEqual("first_field,second_field\r\none,two\r\nsecond_one,second_two\r\n", s.getvalue())
Exemple #9
0
    def connect(self):
        self.accept()
        query_string = self.scope.get('query_string')
        # print(query_string)
        ssh_args = QueryDict(query_string=query_string, encoding='utf-8')

        width = int(ssh_args.get('width'))
        height = int(ssh_args.get('height'))
        port = int(ssh_args.get('port'))

        auth = ssh_args.get('auth')
        ssh_key_name = ssh_args.get('ssh_key')
        passwd = ssh_args.get('password')
        host = ssh_args.get('host')
        user = ssh_args.get('user')

        if passwd:
            passwd = base64.b64decode(passwd).decode('utf-8')
            # password = password
        else:
            passwd = None

        self.ssh = SSH(websocket=self, message=self.message)

        ssh_connect_dict = {
            'host': host,
            'user': user,
            'port': port,
            'timeout': 30,
            'pty_width': width,
            'pty_height': height,
            'password': passwd
        }

        if auth == 'key':
            ssh_key_file = os.path.join(TMP_DIR, ssh_key_name)
            with open(ssh_key_file, 'r') as fp:
                ssh_key = fp.read()

            string_io = StringIO()
            string_io.write(ssh_key)
            string_io.flush()
            string_io.seek()
            ssh_connect_dict['ssh_key'] = string_io

            os.remove(ssh_key_file)
        # print(ssh_connect_dict)
        self.ssh.connect(**ssh_connect_dict)
Exemple #10
0
    def connect(self):
        self.accept()
        print(self.user)
        # user = SshUser.objects.get(username =self.user)
        user = User.objects.filter(username=self.user).first()
        # print(user)
        sshuser = SshUser.objects.filter(username_id=user.id).first()
        # print(sshuser)

        try:
            self.ssh.load_system_host_keys()
            self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

            if sshuser.is_key:
                string_io = StringIO()
                string_io.write(sshuser.ssh_key)
                string_io.flush()
                string_io.seek(0)
                ssh_key = string_io
                passwd = sshuser.password

                if passwd:
                    password = base64.b64decode(passwd).decode('utf-8')
                else:
                    password = None
                key = get_key_obj(paramiko.RSAKey, pkey_obj=ssh_key, password=password) or \
                      get_key_obj(paramiko.DSSKey, pkey_obj=ssh_key, password=password) or \
                      get_key_obj(paramiko.ECDSAKey, pkey_obj=ssh_key, password=password) or \
                      get_key_obj(paramiko.Ed25519Key, pkey_obj=ssh_key, password=password)
                self.ssh.connect(username=user.username, hostname=self.ssh_server_ip, port=22, pkey=key,timeout=5)
            else:
                self.ssh.connect(username=user.username, hostname=self.ssh_server_ip, port=22, password=user.password,timeout=5)

            transport = self.ssh.get_transport()
            self.chan = transport.open_session()
            self.chan.get_pty(term='xterm', width=1400, height=self.height)
            self.chan.invoke_shell()
            # 设置如果3分钟没有任何输入,就断开连接
            self.chan.settimeout(60 * 3)
        except Exception as e:
            print('用户{}通过webssh连接{}失败!原因:{}'.format(user.username, self.ssh_server_ip, e))
            self.send('用户{}通过webssh连接{}失败!原因:{}'.format(user.username, self.ssh_server_ip, e))
            self.close()


        self.t1.setDaemon(True)
        self.t1.start()
Exemple #11
0
    def to_file(self):
        from django.utils.six import StringIO
        # from time import time
        io_file = StringIO()
        # link_file = open('{project_name}_{panel}_links'.format(project_name=self.project.name, panel=self.panel), 'wb')
        io_file.write('{}\r\n'.format('\t'.join(['PID', 'SurveyLink'])))
        for pid in range(self.pid_start_with,
                         self.pid_start_with + self.link_amount):
            # self.generate_link(pid)
            real_pid = self.link_template.format(pid=pid)
            d = {
                'pid': real_pid,
                'chk': get_chk(real_pid),
            }

            lnk = self.get_link(d)

            io_file.write('{pid}\t{survey_link}\r\n'.format(pid=real_pid,
                                                            survey_link=lnk))
        self.times_downloaded += 1
        self.save()
        return io_file.getvalue()
Exemple #12
0
class BufferedFile(File):
    def __init__(self, file_object, mode, name=None):
        self.file_object = file_object
        self.mode = mode
        if 'b' in mode:
            self.stream = BytesIO()
        else:
            self.stream = StringIO()

        self.stream_size = 0

    def close(self):
        self.file_object.close()
        self.stream.close()

    def read(self, size=None):
        if size is None:
            size = -1

        if size == -1 or size > self.stream_size:
            while True:
                position = self.stream.tell()
                chunk = self._get_file_object_chunk()
                if chunk:
                    self.stream_size += len(chunk)
                    self.stream.write(chunk)
                    self.stream.seek(position)
                    if self.stream_size >= size and size != -1:
                        break
                else:
                    break

        if size:
            read_size = min(size, self.stream_size)
            self.stream_size -= read_size
        else:
            read_size = None

        return self.stream.read(read_size)
Exemple #13
0
    def _get_bytes_to_sign(self):
        """
        Creates the message used for signing SNS notifications.
        This is used to verify the bounce message when it is received.
        """

        # Depending on the message type the fields to add to the message
        # differ so we handle that here.
        msg_type = self._data.get('Type')
        if msg_type == 'Notification':
            fields_to_sign = [
                'Message',
                'MessageId',
                'Subject',
                'Timestamp',
                'TopicArn',
                'Type',
            ]
        elif (msg_type == 'SubscriptionConfirmation' or
              msg_type == 'UnsubscribeConfirmation'):
            fields_to_sign = [
                'Message',
                'MessageId',
                'SubscribeURL',
                'Timestamp',
                'Token',
                'TopicArn',
                'Type',
            ]
        else:
            # Unrecognized type
            logger.warning('Unrecognized SNS message Type: "%s"', msg_type)
            return None
        
        outbytes = StringIO()
        for field_name in fields_to_sign:
            field_value = smart_str(self._data.get(field_name, ''),
                                    errors="replace")
            if field_value:
                outbytes.write(field_name)
                outbytes.write("\n")
                outbytes.write(field_value)
                outbytes.write("\n")
         
        return outbytes.getvalue()
def djangularize(src, origin=None):
    out = StringIO('')
    offset = 0
    directive_re = re.compile(r'<(?P<tag_name>\w+)[-=\/\"\'\s\w]*'
                              r'(dj-translatable)[-=\/\"\'\s\w]*\/?>',
                              re.IGNORECASE | re.DOTALL | re.VERBOSE)
    for match in directive_re.finditer(src):
        msg = None
        msg_out = None
        msg_length = 0
        tag_str = repr(match.group())
        out.write(blankout(src[offset:match.start()], 'X'))
        offset = match.start()
        is_closed_tag = ((re.search(r'\/>', tag_str)) is not None)
        trans_attribute = re.search(r'dj-translatable\s*=\s*\"'
                                    r'(?P<attr_name>[-\w\s]+)\"', tag_str)
        if trans_attribute:
            trans_attr_name = trans_attribute.group('attr_name').strip()
            attr_val_re = r''.join([trans_attr_name,
                                    r'\s*=\s*\"(?P<attr_value>[\w\s]+)\"'])
            attr_value = re.search(attr_val_re, tag_str)
            if attr_value:
                msg = attr_value.group('attr_value').strip()
                msg_out = ' gettext(%r) ' % msg
                msg_length = len(msg_out)
                out.write(msg_out)
        if not is_closed_tag:
            tag_name = match.group('tag_name')
            tag_closer_re = re.compile(r'<\/%s>' % tag_name)
            tag_closer = tag_closer_re.search(src, match.end())
            if tag_closer:
                msg = src[match.end():tag_closer.start()]
                msg_out = ' gettext(%r) ' % msg
                msg_length += len(msg_out)
                out.write(msg_out)
        delta = len(tag_str) - msg_length
        if delta > 0:
            out.write(''.join(repeat('X', delta)))
        offset += len(tag_str)
    return out.getvalue()
Exemple #15
0
def jinja_messages_to_python(src, origin=None, **kwargs):
    """
    Convert Jinja2 file to Python preserving only messages.
    """
    output = StringIO('')
    output_lineno = 1
    for (lineno, message, comments, context) in extract_jinja(src, origin):
        for comment in comments:
            output.write(('# %s %s\n' % (COMMENT_TAG, comment)))
            output_lineno += 1
        lines_to_add = (lineno - output_lineno)
        if lines_to_add > 0:  # Try to keep line numbers in sync
            output.write(lines_to_add * '\n')
            output_lineno += lines_to_add
        output.write('gettext(%r),' % (message, ))
    return output.getvalue()
Exemple #16
0
def jinja_messages_to_python(src, origin=None):
    """
    Convert Jinja2 file to Python preserving only messages.
    """
    output = StringIO('')
    output_lineno = 1
    for (lineno, message, comments, context) in extract_jinja(src, origin):
        for comment in comments:
            output.write(('# %s %s\n' % (COMMENT_TAG, comment)))
            output_lineno += 1
        lines_to_add = (lineno - output_lineno)
        if lines_to_add > 0:  # Try to keep line numbers in sync
            output.write(lines_to_add * '\n')
            output_lineno += lines_to_add
        output.write('gettext(%r),' % (message,))
    return output.getvalue()
Exemple #17
0
    def connect(self):
        """
        打开 websocket 连接, 通过前端传入的参数尝试连接 ssh 主机
        :return:
        """
        self.accept()
        self.start_time = timezone.now()
        self.session = self.scope.get('session', None)
        if not self.session.get('islogin', None):    # 未登录直接断开 websocket 连接
            self.message['status'] = 2
            self.message['message'] = 'You are not login in...'
            message = json.dumps(self.message)
            self.send(message)
            self.close(3001)

        self.check_login()

        query_string = self.scope.get('query_string').decode()
        ssh_args = QueryDict(query_string=query_string, encoding='utf-8')

        width = ssh_args.get('width')
        height = ssh_args.get('height')
        width = int(width)
        height = int(height)

        auth = None
        ssh_key_name = '123456'
        hostid = int(ssh_args.get('hostid'))
        try:
            if not self.session['issuperuser']:     # 普通用户判断是否有相关主机或者权限
                hosts = RemoteUserBindHost.objects.filter(
                    Q(id=hostid),
                    Q(user__username=self.session['username']) | Q(group__user__username=self.session['username']),
                ).distinct()
                if not hosts:
                    self.message['status'] = 2
                    self.message['message'] = 'Host is not exist...'
                    message = json.dumps(self.message)
                    self.send(message)
                    self.close(3001)
            self.remote_host = RemoteUserBindHost.objects.get(id=hostid)
            if not self.remote_host.enabled:
                try:
                    self.message['status'] = 2
                    self.message['message'] = 'Host is disabled...'
                    message = json.dumps(self.message)
                    self.send(message)
                    self.close(3001)
                except BaseException:
                    pass
        except BaseException:
            self.message['status'] = 2
            self.message['message'] = 'Host is not exist...'
            message = json.dumps(self.message)
            self.send(message)
            self.close(3001)
        host = self.remote_host.ip
        port = self.remote_host.port
        user = self.remote_host.remote_user.username
        passwd = self.remote_host.remote_user.password
        timeout = 15
        self.ssh = SSH(websocker=self, message=self.message)
        ssh_connect_dict = {
            'host': host,
            'user': user,
            'port': port,
            'timeout': timeout,
            'pty_width': width,
            'pty_height': height,
            'password': passwd,
        }
        if auth == 'key':
            ssh_key_file = os.path.join(TMP_DIR, ssh_key_name)
            with open(ssh_key_file, 'r') as f:
                ssh_key = f.read()

            string_io = StringIO()
            string_io.write(ssh_key)
            string_io.flush()
            string_io.seek(0)
            ssh_connect_dict['ssh_key'] = string_io

            os.remove(ssh_key_file)

        self.ssh.connect(**ssh_connect_dict)
        if self.remote_host.remote_user.enabled:
            if self.session.get('issuperuser', None):  # 超级管理员才能使用 su 跳转功能
                if self.remote_host.remote_user.superusername:
                    self.ssh.su_root(
                        self.remote_host.remote_user.superusername,
                        self.remote_host.remote_user.superpassword,
                        0.3,
                    )
Exemple #18
0
def templatize(src, origin=None):
    """
    Turns a Django template into something that is understood by xgettext. It
    does so by translating the Django translation tags into standard gettext
    function invocations.
    """
    from django.template.base import (Lexer, TOKEN_TEXT, TOKEN_VAR,
        TOKEN_BLOCK, TOKEN_COMMENT, TRANSLATOR_COMMENT_MARK)
    src = force_text(src, settings.FILE_CHARSET)
    out = StringIO('')
    message_context = None
    intrans = False
    inplural = False
    trimmed = False
    singular = []
    plural = []
    incomment = False
    comment = []
    lineno_comment_map = {}
    comment_lineno_cache = None

    def join_tokens(tokens, trim=False):
        message = ''.join(tokens)
        if trim:
            message = trim_whitespace(message)
        return message

    for t in Lexer(src).tokenize():
        if incomment:
            if t.token_type == TOKEN_BLOCK and t.contents == 'endcomment':
                content = ''.join(comment)
                translators_comment_start = None
                for lineno, line in enumerate(content.splitlines(True)):
                    if line.lstrip().startswith(TRANSLATOR_COMMENT_MARK):
                        translators_comment_start = lineno
                for lineno, line in enumerate(content.splitlines(True)):
                    if translators_comment_start is not None and lineno >= translators_comment_start:
                        out.write(' # %s' % line)
                    else:
                        out.write(' #\n')
                incomment = False
                comment = []
            else:
                comment.append(t.contents)
        elif intrans:
            if t.token_type == TOKEN_BLOCK:
                endbmatch = endblock_re.match(t.contents)
                pluralmatch = plural_re.match(t.contents)
                if endbmatch:
                    if inplural:
                        if message_context:
                            out.write(' npgettext(%r, %r, %r,count) ' % (
                                message_context,
                                join_tokens(singular, trimmed),
                                join_tokens(plural, trimmed)))
                        else:
                            out.write(' ngettext(%r, %r, count) ' % (
                                join_tokens(singular, trimmed),
                                join_tokens(plural, trimmed)))
                        for part in singular:
                            out.write(blankout(part, 'S'))
                        for part in plural:
                            out.write(blankout(part, 'P'))
                    else:
                        if message_context:
                            out.write(' pgettext(%r, %r) ' % (
                                message_context,
                                join_tokens(singular, trimmed)))
                        else:
                            out.write(' gettext(%r) ' % join_tokens(singular,
                                                                    trimmed))
                        for part in singular:
                            out.write(blankout(part, 'S'))
                    message_context = None
                    intrans = False
                    inplural = False
                    singular = []
                    plural = []
                elif pluralmatch:
                    inplural = True
                else:
                    filemsg = ''
                    if origin:
                        filemsg = 'file %s, ' % origin
                    raise SyntaxError(
                        "Translation blocks must not include other block tags: "
                        "%s (%sline %d)" % (t.contents, filemsg, t.lineno)
                    )
            elif t.token_type == TOKEN_VAR:
                if inplural:
                    plural.append('%%(%s)s' % t.contents)
                else:
                    singular.append('%%(%s)s' % t.contents)
            elif t.token_type == TOKEN_TEXT:
                contents = t.contents.replace('%', '%%')
                if inplural:
                    plural.append(contents)
                else:
                    singular.append(contents)

        else:
            # Handle comment tokens (`{# ... #}`) plus other constructs on
            # the same line:
            if comment_lineno_cache is not None:
                cur_lineno = t.lineno + t.contents.count('\n')
                if comment_lineno_cache == cur_lineno:
                    if t.token_type != TOKEN_COMMENT:
                        for c in lineno_comment_map[comment_lineno_cache]:
                            filemsg = ''
                            if origin:
                                filemsg = 'file %s, ' % origin
                            warn_msg = ("The translator-targeted comment '%s' "
                                "(%sline %d) was ignored, because it wasn't the last item "
                                "on the line.") % (c, filemsg, comment_lineno_cache)
                            warnings.warn(warn_msg, TranslatorCommentWarning)
                        lineno_comment_map[comment_lineno_cache] = []
                else:
                    out.write('# %s' % ' | '.join(lineno_comment_map[comment_lineno_cache]))
                comment_lineno_cache = None

            if t.token_type == TOKEN_BLOCK:
                imatch = inline_re.match(t.contents)
                bmatch = block_re.match(t.contents)
                cmatches = constant_re.findall(t.contents)
                if imatch:
                    g = imatch.group(1)
                    if g[0] == '"':
                        g = g.strip('"')
                    elif g[0] == "'":
                        g = g.strip("'")
                    g = g.replace('%', '%%')
                    if imatch.group(2):
                        # A context is provided
                        context_match = context_re.match(imatch.group(2))
                        message_context = context_match.group(1)
                        if message_context[0] == '"':
                            message_context = message_context.strip('"')
                        elif message_context[0] == "'":
                            message_context = message_context.strip("'")
                        out.write(' pgettext(%r, %r) ' % (message_context, g))
                        message_context = None
                    else:
                        out.write(' gettext(%r) ' % g)
                elif bmatch:
                    for fmatch in constant_re.findall(t.contents):
                        out.write(' _(%s) ' % fmatch)
                    if bmatch.group(1):
                        # A context is provided
                        context_match = context_re.match(bmatch.group(1))
                        message_context = context_match.group(1)
                        if message_context[0] == '"':
                            message_context = message_context.strip('"')
                        elif message_context[0] == "'":
                            message_context = message_context.strip("'")
                    intrans = True
                    inplural = False
                    trimmed = 'trimmed' in t.split_contents()
                    singular = []
                    plural = []
                elif cmatches:
                    for cmatch in cmatches:
                        out.write(' _(%s) ' % cmatch)
                elif t.contents == 'comment':
                    incomment = True
                else:
                    out.write(blankout(t.contents, 'B'))
            elif t.token_type == TOKEN_VAR:
                parts = t.contents.split('|')
                cmatch = constant_re.match(parts[0])
                if cmatch:
                    out.write(' _(%s) ' % cmatch.group(1))
                for p in parts[1:]:
                    if p.find(':_(') >= 0:
                        out.write(' %s ' % p.split(':', 1)[1])
                    else:
                        out.write(blankout(p, 'F'))
            elif t.token_type == TOKEN_COMMENT:
                if t.contents.lstrip().startswith(TRANSLATOR_COMMENT_MARK):
                    lineno_comment_map.setdefault(t.lineno,
                                                  []).append(t.contents)
                    comment_lineno_cache = t.lineno
            else:
                out.write(blankout(t.contents, 'X'))
    return out.getvalue()
Exemple #19
0
def templatize(src, origin=None):
    """
    Turns a Django template into something that is understood by xgettext. It
    does so by translating the Django translation tags into standard gettext
    function invocations.
    """
    from django.conf import settings
    from django.template import (Lexer, TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK,
            TOKEN_COMMENT, TRANSLATOR_COMMENT_MARK)
    src = force_text(src, settings.FILE_CHARSET)
    out = StringIO()
    message_context = None
    intrans = False
    inplural = False
    singular = []
    plural = []
    incomment = False
    comment = []
    for t in Lexer(src, origin).tokenize():
        if incomment:
            if t.token_type == TOKEN_BLOCK and t.contents == 'endcomment':
                content = ''.join(comment)
                translators_comment_start = None
                for lineno, line in enumerate(content.splitlines(True)):
                    if line.lstrip().startswith(TRANSLATOR_COMMENT_MARK):
                        translators_comment_start = lineno
                for lineno, line in enumerate(content.splitlines(True)):
                    if translators_comment_start is not None and lineno >= translators_comment_start:
                        out.write(' # %s' % line)
                    else:
                        out.write(' #\n')
                incomment = False
                comment = []
            else:
                comment.append(t.contents)
        elif intrans:
            if t.token_type == TOKEN_BLOCK:
                endbmatch = endblock_re.match(t.contents)
                pluralmatch = plural_re.match(t.contents)
                if endbmatch:
                    if inplural:
                        if message_context:
                            out.write(' npgettext(%r, %r, %r,count) ' % (message_context, ''.join(singular), ''.join(plural)))
                        else:
                            out.write(' ngettext(%r, %r, count) ' % (''.join(singular), ''.join(plural)))
                        for part in singular:
                            out.write(blankout(part, 'S'))
                        for part in plural:
                            out.write(blankout(part, 'P'))
                    else:
                        if message_context:
                            out.write(' pgettext(%r, %r) ' % (message_context, ''.join(singular)))
                        else:
                            out.write(' gettext(%r) ' % ''.join(singular))
                        for part in singular:
                            out.write(blankout(part, 'S'))
                    message_context = None
                    intrans = False
                    inplural = False
                    singular = []
                    plural = []
                elif pluralmatch:
                    inplural = True
                else:
                    filemsg = ''
                    if origin:
                        filemsg = 'file %s, ' % origin
                    raise SyntaxError("Translation blocks must not include other block tags: %s (%sline %d)" % (t.contents, filemsg, t.lineno))
            elif t.token_type == TOKEN_VAR:
                if inplural:
                    plural.append('%%(%s)s' % t.contents)
                else:
                    singular.append('%%(%s)s' % t.contents)
            elif t.token_type == TOKEN_TEXT:
                contents = one_percent_re.sub('%%', t.contents)
                if inplural:
                    plural.append(contents)
                else:
                    singular.append(contents)
        else:
            if t.token_type == TOKEN_BLOCK:
                imatch = inline_re.match(t.contents)
                bmatch = block_re.match(t.contents)
                cmatches = constant_re.findall(t.contents)
                # DJANGO_CHANGE(cpauya):
                # For handlebars templates using `{{_ "text here" }}`.
                hbmatches = constant_hb_re.findall(t.contents)
                if imatch:
                    g = imatch.group(1)
                    if g[0] == '"':
                        g = g.strip('"')
                    elif g[0] == "'":
                        g = g.strip("'")
                    g = one_percent_re.sub('%%', g)
                    if imatch.group(2):
                        # A context is provided
                        context_match = context_re.match(imatch.group(2))
                        message_context = context_match.group(1)
                        if message_context[0] == '"':
                            message_context = message_context.strip('"')
                        elif message_context[0] == "'":
                            message_context = message_context.strip("'")
                        out.write(' pgettext(%r, %r) ' % (message_context, g))
                        message_context = None
                    else:
                        out.write(' gettext(%r) ' % g)
                elif bmatch:
                    for fmatch in constant_re.findall(t.contents):
                        out.write(' _(%s) ' % fmatch)
                    # DJANGO_CHANGE(cpauya):
                    # For handlebars templates using `{{_ "text here" }}`.
                    for hbmatch in constant_hb_re.findall(t.contents):
                        out.write(' _(%s) ' % hbmatch)
                    if bmatch.group(1):
                        # A context is provided
                        context_match = context_re.match(bmatch.group(1))
                        message_context = context_match.group(1)
                        if message_context[0] == '"':
                            message_context = message_context.strip('"')
                        elif message_context[0] == "'":
                            message_context = message_context.strip("'")
                    intrans = True
                    inplural = False
                    singular = []
                    plural = []
                elif cmatches:
                    for cmatch in cmatches:
                        out.write(' _(%s) ' % cmatch)
                # DJANGO_CHANGE(cpauya):
                # For handlebars templates using `{{_ "text here" }}`.
                elif hbmatches:
                    for hbmatch in hbmatches:
                        out.write(' _(%s) ' % hbmatch)
                elif t.contents == 'comment':
                    incomment = True
                else:
                    out.write(blankout(t.contents, 'B'))
            elif t.token_type == TOKEN_VAR:
                parts = t.contents.split('|')
                cmatch = constant_re.match(parts[0])
                if cmatch:
                    out.write(' _(%s) ' % cmatch.group(1))
                # DJANGO_CHANGE(cpauya):
                # For handlebars templates using `{{_ "text here" }}`.
                hbmatch = constant_hb_re.match(parts[0])
                if hbmatch:
                    out.write(' _(%s) ' % hbmatch.group(1))
                for p in parts[1:]:
                    if p.find(':_(') >= 0:
                        out.write(' %s ' % p.split(':',1)[1])
                    else:
                        out.write(blankout(p, 'F'))
            elif t.token_type == TOKEN_COMMENT:
                out.write(' # %s' % t.contents)
            else:
                out.write(blankout(t.contents, 'X'))
    return force_str(out.getvalue())
Exemple #20
0
def templatize(src, origin=None):
    """
    Turns a Django template into something that is understood by xgettext. It
    does so by translating the Django translation tags into standard gettext
    function invocations.
    """
    from django.template.base import (Lexer, TOKEN_TEXT, TOKEN_VAR,
                                      TOKEN_BLOCK, TOKEN_COMMENT,
                                      TRANSLATOR_COMMENT_MARK)
    src = force_text(src, settings.FILE_CHARSET)
    out = StringIO('')
    message_context = None
    intrans = False
    inplural = False
    trimmed = False
    singular = []
    plural = []
    incomment = False
    comment = []
    lineno_comment_map = {}
    comment_lineno_cache = None

    def join_tokens(tokens, trim=False):
        message = ''.join(tokens)
        if trim:
            message = trim_whitespace(message)
        return message

    for t in Lexer(src).tokenize():
        if incomment:
            if t.token_type == TOKEN_BLOCK and t.contents == 'endcomment':
                content = ''.join(comment)
                translators_comment_start = None
                for lineno, line in enumerate(content.splitlines(True)):
                    if line.lstrip().startswith(TRANSLATOR_COMMENT_MARK):
                        translators_comment_start = lineno
                for lineno, line in enumerate(content.splitlines(True)):
                    if translators_comment_start is not None and lineno >= translators_comment_start:
                        out.write(' # %s' % line)
                    else:
                        out.write(' #\n')
                incomment = False
                comment = []
            else:
                comment.append(t.contents)
        elif intrans:
            if t.token_type == TOKEN_BLOCK:
                endbmatch = endblock_re.match(t.contents)
                pluralmatch = plural_re.match(t.contents)
                if endbmatch:
                    if inplural:
                        if message_context:
                            out.write(' npgettext(%r, %r, %r,count) ' %
                                      (message_context,
                                       join_tokens(singular, trimmed),
                                       join_tokens(plural, trimmed)))
                        else:
                            out.write(' ngettext(%r, %r, count) ' %
                                      (join_tokens(singular, trimmed),
                                       join_tokens(plural, trimmed)))
                        for part in singular:
                            out.write(blankout(part, 'S'))
                        for part in plural:
                            out.write(blankout(part, 'P'))
                    else:
                        if message_context:
                            out.write(' pgettext(%r, %r) ' %
                                      (message_context,
                                       join_tokens(singular, trimmed)))
                        else:
                            out.write(' gettext(%r) ' %
                                      join_tokens(singular, trimmed))
                        for part in singular:
                            out.write(blankout(part, 'S'))
                    message_context = None
                    intrans = False
                    inplural = False
                    singular = []
                    plural = []
                elif pluralmatch:
                    inplural = True
                else:
                    filemsg = ''
                    if origin:
                        filemsg = 'file %s, ' % origin
                    raise SyntaxError(
                        "Translation blocks must not include other block tags: "
                        "%s (%sline %d)" % (t.contents, filemsg, t.lineno))
            elif t.token_type == TOKEN_VAR:
                if inplural:
                    plural.append('%%(%s)s' % t.contents)
                else:
                    singular.append('%%(%s)s' % t.contents)
            elif t.token_type == TOKEN_TEXT:
                contents = t.contents.replace('%', '%%')
                if inplural:
                    plural.append(contents)
                else:
                    singular.append(contents)

        else:
            # Handle comment tokens (`{# ... #}`) plus other constructs on
            # the same line:
            if comment_lineno_cache is not None:
                cur_lineno = t.lineno + t.contents.count('\n')
                if comment_lineno_cache == cur_lineno:
                    if t.token_type != TOKEN_COMMENT:
                        for c in lineno_comment_map[comment_lineno_cache]:
                            filemsg = ''
                            if origin:
                                filemsg = 'file %s, ' % origin
                            warn_msg = (
                                "The translator-targeted comment '%s' "
                                "(%sline %d) was ignored, because it wasn't the last item "
                                "on the line.") % (c, filemsg,
                                                   comment_lineno_cache)
                            warnings.warn(warn_msg, TranslatorCommentWarning)
                        lineno_comment_map[comment_lineno_cache] = []
                else:
                    out.write(
                        '# %s' %
                        ' | '.join(lineno_comment_map[comment_lineno_cache]))
                comment_lineno_cache = None

            if t.token_type == TOKEN_BLOCK:
                imatch = inline_re.match(t.contents)
                bmatch = block_re.match(t.contents)
                cmatches = constant_re.findall(t.contents)
                if imatch:
                    g = imatch.group(1)
                    if g[0] == '"':
                        g = g.strip('"')
                    elif g[0] == "'":
                        g = g.strip("'")
                    g = g.replace('%', '%%')
                    if imatch.group(2):
                        # A context is provided
                        context_match = context_re.match(imatch.group(2))
                        message_context = context_match.group(1)
                        if message_context[0] == '"':
                            message_context = message_context.strip('"')
                        elif message_context[0] == "'":
                            message_context = message_context.strip("'")
                        out.write(' pgettext(%r, %r) ' % (message_context, g))
                        message_context = None
                    else:
                        out.write(' gettext(%r) ' % g)
                elif bmatch:
                    for fmatch in constant_re.findall(t.contents):
                        out.write(' _(%s) ' % fmatch)
                    if bmatch.group(1):
                        # A context is provided
                        context_match = context_re.match(bmatch.group(1))
                        message_context = context_match.group(1)
                        if message_context[0] == '"':
                            message_context = message_context.strip('"')
                        elif message_context[0] == "'":
                            message_context = message_context.strip("'")
                    intrans = True
                    inplural = False
                    trimmed = 'trimmed' in t.split_contents()
                    singular = []
                    plural = []
                elif cmatches:
                    for cmatch in cmatches:
                        out.write(' _(%s) ' % cmatch)
                elif t.contents == 'comment':
                    incomment = True
                else:
                    out.write(blankout(t.contents, 'B'))
            elif t.token_type == TOKEN_VAR:
                parts = t.contents.split('|')
                cmatch = constant_re.match(parts[0])
                if cmatch:
                    out.write(' _(%s) ' % cmatch.group(1))
                for p in parts[1:]:
                    if p.find(':_(') >= 0:
                        out.write(' %s ' % p.split(':', 1)[1])
                    else:
                        out.write(blankout(p, 'F'))
            elif t.token_type == TOKEN_COMMENT:
                if t.contents.lstrip().startswith(TRANSLATOR_COMMENT_MARK):
                    lineno_comment_map.setdefault(t.lineno,
                                                  []).append(t.contents)
                    comment_lineno_cache = t.lineno
            else:
                out.write(blankout(t.contents, 'X'))
    return out.getvalue()
Exemple #21
0
 def to_str(self):
     fd = StringIO()
     fd.write('# -*- coding: utf-8 -*-\n')
     for k, v in self.values.items():
         fd.write('%s = %r\n' % (k, v))
     return fd.getvalue()
Exemple #22
0
    def connect(self):
        """
        打开 websocket 连接, 通过前端传入的参数尝试连接 ssh 主机
        :return:
        """
        self.accept()
        query_string = self.scope.get('query_string')
        ssh_args = QueryDict(query_string=query_string, encoding='utf-8')

        width = ssh_args.get('width')
        height = ssh_args.get('height')
        port = ssh_args.get('port')

        width = int(width)
        height = int(height)
        port = int(port)

        auth = ssh_args.get('auth')
        ssh_key_name = ssh_args.get('ssh_key')
        passwd = ssh_args.get('password')

        host = ssh_args.get('host')
        user = ssh_args.get('user')

        connect_time = time.time()
        filename = '%s.%s.%d.cast' % (host, user, connect_time)  # 文件名

        # 构建录像文件header
        record_log(
            type = 'header', 
            data = {
            "version": 2,
            "width": width,
            "height": height,
            "timestamp": connect_time,
            "env": {
                "SHELL": "/bin/bash",
                "TERM": 'xterm-256color'
            },
            "title": "zili-webssh"
            },
            connect_time = connect_time,
            host = host,
            user = user,
            filename = filename
        )

        if passwd:
            passwd = base64.b64decode(passwd).decode('utf-8')
        else:
            passwd = None

        self.ssh = SSH(websocker=self, message=self.message)

        ssh_connect_dict = {
            'host': host,
            'user': user,
            'port': port,
            'timeout': 30,
            'pty_width': width,
            'pty_height': height,
            'password': passwd,
            'filename':filename,
            'connect_time':connect_time
        }

        if auth == 'key':
            ssh_key_file = os.path.join(TMP_DIR, ssh_key_name)
            with open(ssh_key_file, 'r') as f:
                ssh_key = f.read()

            string_io = StringIO()
            string_io.write(ssh_key)
            string_io.flush()
            string_io.seek(0)
            ssh_connect_dict['ssh_key'] = string_io

            os.remove(ssh_key_file)


        self.ssh.connect(**ssh_connect_dict)
Exemple #23
0
    def connect(self):
        try:
            self.accept()
            query_string = self.scope['query_string']
            connet_argv = QueryDict(query_string=query_string,
                                    encoding='utf-8')
            unique = connet_argv.get('unique')
            width = connet_argv.get('width')
            height = connet_argv.get('height')

            width = int(width)
            height = int(height)

            connect_info = models.HostTmp.objects.get(unique=unique)

            host = connect_info.host
            port = connect_info.port
            user = connect_info.user
            auth = connect_info.auth
            pwd = connect_info.password
            pkey = connect_info.pkey
            #print("web=============================pkey:",pkey)

            connect_info.delete()

            if pwd:
                password = base64.b64decode(pwd).decode('utf-8')  #这里解编码密码
            else:
                password = None

            self.ssh = SSH(websocker=self, message=self.message)

            if auth == 'key':
                pkey = pkey
                obj = StringIO()
                obj.write(pkey)
                obj.flush()
                obj.seek(0)
                self.pkey = obj
                #print("web=============================pkey:",self.pkey)

                self.ssh.connect(host=host,
                                 user=user,
                                 password=password,
                                 pkey=self.pkey,
                                 port=port,
                                 pty_width=width,
                                 pty_height=height)
            else:
                self.ssh.connect(host=host,
                                 user=user,
                                 password=password,
                                 port=port,
                                 pty_width=width,
                                 pty_height=height)
        except Exception as e:  #因为上面解码时:base64.b64decode(pwd).decode('utf-8'),字符串原本没有编码,
            # 所以导致binascii.Error: Incorrect padding报错,所以后面添加密码时需要进行
            # 编码:base64.b64encode(b"root123456."),修改后,密钥登陆的密码也需要编码
            # 原因是在webssh.js中编码了一下密钥登陆的password字段:var password = window.btoa(pwd); 已修改
            # 而使用密码登陆的没有经过此步骤,直接由后端查询数据库得到了
            print(e)
            self.message['status'] = 1
            self.message['message'] = str(e)
            message = json.dumps(self.message)
            self.send(message)
            self.close()
Exemple #24
0
    def connect(self):
        """
        打开 websocket 连接, 通过前端传入的参数尝试连接 ssh 主机
        :return:
        """
        self.accept()
        async_to_sync(self.channel_layer.group_add)(self.group,
                                                    self.channel_name)  # 加入组
        self.start_time = timezone.now()
        self.session = self.scope.get('session', None)
        if not self.session.get('islogin', None):  # 未登录直接断开 websocket 连接
            self.message['status'] = 2
            self.message['message'] = 'You are not login in...'
            message = json.dumps(self.message)
            if self.send_flag == 0:
                self.send(message)
            elif self.send_flag == 1:
                async_to_sync(self.channel_layer.group_send)(self.group, {
                    "type": "chat.message",
                    "text": message,
                })
            self.close(3001)

        if 'webssh终端' not in self.session[
                settings.INIT_PERMISSION]['titles']:  # 判断权限
            self.message['status'] = 2
            self.message['message'] = '无权限'
            message = json.dumps(self.message)
            if self.send_flag == 0:
                self.send(message)
            elif self.send_flag == 1:
                async_to_sync(self.channel_layer.group_send)(self.group, {
                    "type": "chat.message",
                    "text": message,
                })
            self.close(3001)

        self.check_login()
        query_string = self.scope.get('query_string').decode()
        ssh_args = QueryDict(query_string=query_string, encoding='utf-8')
        width = ssh_args.get('width')
        height = ssh_args.get('height')
        width = int(width)
        height = int(height)
        auth = None
        ssh_key_name = '123456'
        hostid = int(ssh_args.get('hostid'))
        try:
            if not self.session['issuperuser']:  # 普通用户判断是否有相关主机或者权限
                hosts = RemoteUserBindHost.objects.filter(
                    Q(id=hostid),
                    Q(enabled=True),
                    Q(user__username=self.session['username'])
                    | Q(group__user__username=self.session['username']),
                ).distinct()
            else:
                hosts = RemoteUserBindHost.objects.filter(
                    Q(id=hostid),
                    Q(enabled=True),
                ).distinct()
            if not hosts:
                self.message['status'] = 2
                self.message['message'] = 'Host is not exist...'
                message = json.dumps(self.message)
                if self.send_flag == 0:
                    self.send(message)
                elif self.send_flag == 1:
                    async_to_sync(self.channel_layer.group_send)(
                        self.group, {
                            "type": "chat.message",
                            "text": message,
                        })
                self.close(3001)
            self.remote_host = RemoteUserBindHost.objects.get(id=hostid)
        except Exception:
            print(traceback.format_exc())
            self.message['status'] = 2
            self.message['message'] = 'Host is not exist...'
            message = json.dumps(self.message)
            if self.send_flag == 0:
                self.send(message)
            elif self.send_flag == 1:
                async_to_sync(self.channel_layer.group_send)(self.group, {
                    "type": "chat.message",
                    "text": message,
                })
            self.close(3001)

        host = self.remote_host.ip
        port = self.remote_host.port
        user = self.remote_host.remote_user.username
        passwd = decrypt(self.remote_host.remote_user.password)
        timeout = 15
        self.ssh = SSH(websocker=self, message=self.message)
        ssh_connect_dict = {
            'host': host,
            'user': user,
            'port': port,
            'timeout': timeout,
            'pty_width': width,
            'pty_height': height,
            'password': passwd,
        }
        if auth == 'key':
            ssh_key_file = os.path.join(TMP_DIR, ssh_key_name)
            with open(ssh_key_file, 'r') as f:
                ssh_key = f.read()

            string_io = StringIO()
            string_io.write(ssh_key)
            string_io.flush()
            string_io.seek(0)
            ssh_connect_dict['ssh_key'] = string_io

            os.remove(ssh_key_file)

        self.ssh.connect(**ssh_connect_dict)
        if self.remote_host.remote_user.enabled:
            if self.remote_host.remote_user.superusername:
                if '登陆后su跳转超级用户' in self.session[
                        settings.INIT_PERMISSION]['titles']:  # 判断权限
                    self.ssh.su_root(
                        self.remote_host.remote_user.superusername,
                        decrypt(self.remote_host.remote_user.superpassword),
                        1,
                    )

        for i in self.scope['headers']:
            if i[0].decode('utf-8') == 'user-agent':
                self.user_agent = i[1].decode('utf-8')
                break

        for i in self.scope['headers']:
            if i[0].decode('utf-8') == 'x-real-ip':
                self.client = i[1].decode('utf-8')
                break
            if i[0].decode('utf-8') == 'x-forwarded-for':
                self.client = i[1].decode('utf-8').split(',')[0]
                break
            self.client = self.scope['client'][0]

        data = {
            'name': self.channel_name,
            'group': self.group,
            'user': self.session.get('username'),
            'host': host,
            'username': user,
            'protocol': self.remote_host.protocol,
            'port': port,
            'type': 1,  # 1 webssh
            'address': self.client,
            'useragent': self.user_agent,
        }
        TerminalSession.objects.create(**data)
Exemple #25
0
def templatize(src, origin=None):
    """
    Turns a Django template into something that is understood by xgettext. It
    does so by translating the Django translation tags into standard gettext
    function invocations.
    """
    from django.template.base import Lexer, TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK, TOKEN_COMMENT, TRANSLATOR_COMMENT_MARK

    src = force_text(src, settings.FILE_CHARSET)
    out = StringIO("")
    message_context = None
    intrans = False
    inplural = False
    trimmed = False
    singular = []
    plural = []
    incomment = False
    comment = []
    lineno_comment_map = {}
    comment_lineno_cache = None
    # Adding the u prefix allows gettext to recognize the Unicode string
    # (#26093).
    raw_prefix = "u" if six.PY3 else ""

    def join_tokens(tokens, trim=False):
        message = "".join(tokens)
        if trim:
            message = trim_whitespace(message)
        return message

    for t in Lexer(src).tokenize():
        if incomment:
            if t.token_type == TOKEN_BLOCK and t.contents == "endcomment":
                content = "".join(comment)
                translators_comment_start = None
                for lineno, line in enumerate(content.splitlines(True)):
                    if line.lstrip().startswith(TRANSLATOR_COMMENT_MARK):
                        translators_comment_start = lineno
                for lineno, line in enumerate(content.splitlines(True)):
                    if translators_comment_start is not None and lineno >= translators_comment_start:
                        out.write(" # %s" % line)
                    else:
                        out.write(" #\n")
                incomment = False
                comment = []
            else:
                comment.append(t.contents)
        elif intrans:
            if t.token_type == TOKEN_BLOCK:
                endbmatch = endblock_re.match(t.contents)
                pluralmatch = plural_re.match(t.contents)
                if endbmatch:
                    if inplural:
                        if message_context:
                            out.write(
                                " npgettext({p}{!r}, {p}{!r}, {p}{!r},count) ".format(
                                    message_context,
                                    join_tokens(singular, trimmed),
                                    join_tokens(plural, trimmed),
                                    p=raw_prefix,
                                )
                            )
                        else:
                            out.write(
                                " ngettext({p}{!r}, {p}{!r}, count) ".format(
                                    join_tokens(singular, trimmed), join_tokens(plural, trimmed), p=raw_prefix
                                )
                            )
                        for part in singular:
                            out.write(blankout(part, "S"))
                        for part in plural:
                            out.write(blankout(part, "P"))
                    else:
                        if message_context:
                            out.write(
                                " pgettext({p}{!r}, {p}{!r}) ".format(
                                    message_context, join_tokens(singular, trimmed), p=raw_prefix
                                )
                            )
                        else:
                            out.write(" gettext({p}{!r}) ".format(join_tokens(singular, trimmed), p=raw_prefix))
                        for part in singular:
                            out.write(blankout(part, "S"))
                    message_context = None
                    intrans = False
                    inplural = False
                    singular = []
                    plural = []
                elif pluralmatch:
                    inplural = True
                else:
                    filemsg = ""
                    if origin:
                        filemsg = "file %s, " % origin
                    raise SyntaxError(
                        "Translation blocks must not include other block tags: "
                        "%s (%sline %d)" % (t.contents, filemsg, t.lineno)
                    )
            elif t.token_type == TOKEN_VAR:
                if inplural:
                    plural.append("%%(%s)s" % t.contents)
                else:
                    singular.append("%%(%s)s" % t.contents)
            elif t.token_type == TOKEN_TEXT:
                contents = t.contents.replace("%", "%%")
                if inplural:
                    plural.append(contents)
                else:
                    singular.append(contents)

        else:
            # Handle comment tokens (`{# ... #}`) plus other constructs on
            # the same line:
            if comment_lineno_cache is not None:
                cur_lineno = t.lineno + t.contents.count("\n")
                if comment_lineno_cache == cur_lineno:
                    if t.token_type != TOKEN_COMMENT:
                        for c in lineno_comment_map[comment_lineno_cache]:
                            filemsg = ""
                            if origin:
                                filemsg = "file %s, " % origin
                            warn_msg = (
                                "The translator-targeted comment '%s' "
                                "(%sline %d) was ignored, because it wasn't the last item "
                                "on the line."
                            ) % (c, filemsg, comment_lineno_cache)
                            warnings.warn(warn_msg, TranslatorCommentWarning)
                        lineno_comment_map[comment_lineno_cache] = []
                else:
                    out.write("# %s" % " | ".join(lineno_comment_map[comment_lineno_cache]))
                comment_lineno_cache = None

            if t.token_type == TOKEN_BLOCK:
                imatch = inline_re.match(t.contents)
                bmatch = block_re.match(t.contents)
                cmatches = constant_re.findall(t.contents)
                if imatch:
                    g = imatch.group(1)
                    if g[0] == '"':
                        g = g.strip('"')
                    elif g[0] == "'":
                        g = g.strip("'")
                    g = g.replace("%", "%%")
                    if imatch.group(2):
                        # A context is provided
                        context_match = context_re.match(imatch.group(2))
                        message_context = context_match.group(1)
                        if message_context[0] == '"':
                            message_context = message_context.strip('"')
                        elif message_context[0] == "'":
                            message_context = message_context.strip("'")
                        out.write(" pgettext({p}{!r}, {p}{!r}) ".format(message_context, g, p=raw_prefix))
                        message_context = None
                    else:
                        out.write(" gettext({p}{!r}) ".format(g, p=raw_prefix))
                elif bmatch:
                    for fmatch in constant_re.findall(t.contents):
                        out.write(" _(%s) " % fmatch)
                    if bmatch.group(1):
                        # A context is provided
                        context_match = context_re.match(bmatch.group(1))
                        message_context = context_match.group(1)
                        if message_context[0] == '"':
                            message_context = message_context.strip('"')
                        elif message_context[0] == "'":
                            message_context = message_context.strip("'")
                    intrans = True
                    inplural = False
                    trimmed = "trimmed" in t.split_contents()
                    singular = []
                    plural = []
                elif cmatches:
                    for cmatch in cmatches:
                        out.write(" _(%s) " % cmatch)
                elif t.contents == "comment":
                    incomment = True
                else:
                    out.write(blankout(t.contents, "B"))
            elif t.token_type == TOKEN_VAR:
                parts = t.contents.split("|")
                cmatch = constant_re.match(parts[0])
                if cmatch:
                    out.write(" _(%s) " % cmatch.group(1))
                for p in parts[1:]:
                    if p.find(":_(") >= 0:
                        out.write(" %s " % p.split(":", 1)[1])
                    else:
                        out.write(blankout(p, "F"))
            elif t.token_type == TOKEN_COMMENT:
                if t.contents.lstrip().startswith(TRANSLATOR_COMMENT_MARK):
                    lineno_comment_map.setdefault(t.lineno, []).append(t.contents)
                    comment_lineno_cache = t.lineno
            else:
                out.write(blankout(t.contents, "X"))
    return out.getvalue()
Exemple #26
0
def templatize(src, origin=None):
    """
    Turns a Django template into something that is understood by xgettext. It
    does so by translating the Django translation tags into standard gettext
    function invocations.
    """
    from django.conf import settings
    from django.template import (Lexer, TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK,
                                 TOKEN_COMMENT, TRANSLATOR_COMMENT_MARK)
    src = src.decode(settings.FILE_CHARSET)
    out = StringIO()
    message_context = None
    intrans = False
    inplural = False
    singular = []
    plural = []
    incomment = False
    comment = []
    for t in Lexer(src, origin).tokenize():
        if incomment:
            if t.token_type == TOKEN_BLOCK and t.contents == 'endcomment':
                content = ''.join(comment)
                translators_comment_start = None
                for lineno, line in enumerate(content.splitlines(True)):
                    if line.lstrip().startswith(TRANSLATOR_COMMENT_MARK):
                        translators_comment_start = lineno
                for lineno, line in enumerate(content.splitlines(True)):
                    if translators_comment_start is not None and lineno >= translators_comment_start:
                        out.write(' # %s' % line)
                    else:
                        out.write(' #\n')
                incomment = False
                comment = []
            else:
                comment.append(t.contents)
        elif intrans:
            if t.token_type == TOKEN_BLOCK:
                endbmatch = endblock_re.match(t.contents)
                pluralmatch = plural_re.match(t.contents)
                if endbmatch:
                    if inplural:
                        if message_context:
                            out.write(' npgettext(%r, %r, %r,count) ' %
                                      (message_context, ''.join(singular),
                                       ''.join(plural)))
                        else:
                            out.write(' ngettext(%r, %r, count) ' %
                                      (''.join(singular), ''.join(plural)))
                        for part in singular:
                            out.write(blankout(part, 'S'))
                        for part in plural:
                            out.write(blankout(part, 'P'))
                    else:
                        if message_context:
                            out.write(' pgettext(%r, %r) ' %
                                      (message_context, ''.join(singular)))
                        else:
                            out.write(' gettext(%r) ' % ''.join(singular))
                        for part in singular:
                            out.write(blankout(part, 'S'))
                    message_context = None
                    intrans = False
                    inplural = False
                    singular = []
                    plural = []
                elif pluralmatch:
                    inplural = True
                else:
                    filemsg = ''
                    if origin:
                        filemsg = 'file %s, ' % origin
                    raise SyntaxError(
                        "Translation blocks must not include other block tags: %s (%sline %d)"
                        % (t.contents, filemsg, t.lineno))
            elif t.token_type == TOKEN_VAR:
                if inplural:
                    plural.append('%%(%s)s' % t.contents)
                else:
                    singular.append('%%(%s)s' % t.contents)
            elif t.token_type == TOKEN_TEXT:
                contents = one_percent_re.sub('%%', t.contents)
                if inplural:
                    plural.append(contents)
                else:
                    singular.append(contents)
        else:
            if t.token_type == TOKEN_BLOCK:
                imatch = inline_re.match(t.contents)
                bmatch = block_re.match(t.contents)
                cmatches = constant_re.findall(t.contents)
                if imatch:
                    g = imatch.group(1)
                    if g[0] == '"':
                        g = g.strip('"')
                    elif g[0] == "'":
                        g = g.strip("'")
                    g = one_percent_re.sub('%%', g)
                    if imatch.group(2):
                        # A context is provided
                        context_match = context_re.match(imatch.group(2))
                        message_context = context_match.group(1)
                        if message_context[0] == '"':
                            message_context = message_context.strip('"')
                        elif message_context[0] == "'":
                            message_context = message_context.strip("'")
                        out.write(' pgettext(%r, %r) ' % (message_context, g))
                        message_context = None
                    else:
                        out.write(' gettext(%r) ' % g)
                elif bmatch:
                    for fmatch in constant_re.findall(t.contents):
                        out.write(' _(%s) ' % fmatch)
                    if bmatch.group(1):
                        # A context is provided
                        context_match = context_re.match(bmatch.group(1))
                        message_context = context_match.group(1)
                        if message_context[0] == '"':
                            message_context = message_context.strip('"')
                        elif message_context[0] == "'":
                            message_context = message_context.strip("'")
                    intrans = True
                    inplural = False
                    singular = []
                    plural = []
                elif cmatches:
                    for cmatch in cmatches:
                        out.write(' _(%s) ' % cmatch)
                elif t.contents == 'comment':
                    incomment = True
                else:
                    out.write(blankout(t.contents, 'B'))
            elif t.token_type == TOKEN_VAR:
                parts = t.contents.split('|')
                cmatch = constant_re.match(parts[0])
                if cmatch:
                    out.write(' _(%s) ' % cmatch.group(1))
                for p in parts[1:]:
                    if p.find(':_(') >= 0:
                        out.write(' %s ' % p.split(':', 1)[1])
                    else:
                        out.write(blankout(p, 'F'))
            elif t.token_type == TOKEN_COMMENT:
                out.write(' # %s' % t.contents)
            else:
                out.write(blankout(t.contents, 'X'))
    return out.getvalue().encode('utf-8')
    def connect(self):
        """
        建立WebSocket连接,并实例化SSHBridge类,在这个对象中建立SSH连接,放在 self.ssh_channel 通道中
        :return:
        """
        self.host_id = self.scope['url_route']['kwargs'].get('host_id')
        # 获取session中的值
        self.simple_user = self.scope["user"].username
        # print('【Web  --websocket-->  WS】建立WebSocket通道,当前连接用户:', self.simple_user)

        host_obj = Host.objects.get(id=self.host_id)

        self.accept()

        # WebSocket连接成功后,连接ssh
        query_string = self.scope.get('query_string')
        ws_args = QueryDict(query_string=query_string, encoding='utf-8')
        # # print(ws_args)
        # <QueryDict: {'user': ['admin'], 'host': ['192.168.96.20'], 'port': ['22'], 'auth': ['pwd'], 'pwd': ['ZGphbmdvYWRtaW4='], 'key': [''], 'width': ['113'], 'height': ['43']}>
        # 根据参数判断是否是协作
        team = ws_args.get('team')
        if team:
            self.is_team = True
            self.team_name = "team_{}".format(self.host_id)  # 加到这个通道组
            async_to_sync(self.channel_layer.group_add)(
                self.team_name,
                self.channel_name
            )
            # 用户连接时,同一群组发送消息
            self.send_message_or_team(json.dumps(
                {'flag': 'user', 'message': '用户 {} 已连接本终端'.format(self.simple_user)}))

        width = ws_args.get('width')
        height = ws_args.get('height')
        width = int(width)
        height = int(height)  # ssh连接要求int类型:required argument is an integer

        ssh_connect_dict = {}

        user = self.simple_user
        host = host_obj.ip
        port = host_obj.ssh_port
        port = int(port)
        auth = host_obj.ssh_user
        pwd = host_obj.ssh_passwd
        # if pwd:
        #     pwd = base64.b64decode(pwd).decode('utf-8')
        sshkey_filename_path = host_obj.ssh_key.ssh_key.path if host_obj.ssh_key else None

        ssh_connect_dict = {
            'host': host,
            'user': auth,
            'port': port,
            'timeout': 30,
            'pty_width': width,
            'pty_height': height,
            'pwd': pwd
        }

        if sshkey_filename_path:
            if not os.path.exists(sshkey_filename_path):
                self.send(json.dumps(
                    {'flag': 'error', 'message': '密钥文件不存在'}))

            else:
                try:
                    f = open(sshkey_filename_path, 'r', encoding='utf-8')
                    key = f.read()
                    string_io = StringIO()
                    string_io.write(key)
                    string_io.flush()
                    string_io.seek(0)
                    ssh_connect_dict['key'] = string_io

                    # os.remove(sshkey_filename_path)  # 用完之后删除key文件
                except BaseException as e:
                    # print('打开密钥文件出错', e)
                    pass

        # 建立SSH连接
        self.ssh = SSHBridge(websocket=self, simpleuser=self.simple_user)
        # print('【WS  --SSHBridge-->  SSH】连接SSH参数:', ssh_connect_dict)
        self.ssh.connect(**ssh_connect_dict)