repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
jumpserver
apps/common/db/managers.py
.py
from django.db import models class DebugQueryManager(models.Manager): def get_queryset(self): import traceback lines = traceback.format_stack() print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>") for line in lines[-10:-1]: print(line) print("<<<<<<<<<<<<<<<<<<<<<<<<<<<<") ...
14
383
jumpserver
apps/common/db/aggregates.py
.py
from django.db.models import Aggregate class GroupConcat(Aggregate): function = 'GROUP_CONCAT' template = '%(function)s(%(expressions)s %(order_by)s %(separator)s)' allow_distinct = False def __init__(self, expression, order_by=None, separator=',', **extra): order_by_clause = '' if or...
28
809
jumpserver
apps/common/db/validators.py
.py
from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ class PortRangeValidator: def __init__(self, start=1, end=65535): self.start = start self.end = end self.error_message = _("Invalid port range, should be like and within {}-{}").format...
23
786
jumpserver
apps/common/plugins/es.py
.py
# -*- coding: utf-8 -*- # import datetime import inspect import sys if sys.version_info.major == 3 and sys.version_info.minor >= 10: from collections.abc import Iterable else: from collections import Iterable from functools import reduce, partial from itertools import groupby from uuid import UUID from djang...
618
19,854
jumpserver
apps/common/templatetags/common_tags.py
.py
# ~*~ coding: utf-8 ~*~ from django import template from django.utils import timezone from django.utils.translation import gettext as _ from django.utils.html import escape from django import forms register = template.Library() @register.filter def join_queryset_attr(queryset, attr, delimiter=', '): return deli...
131
2,838
jumpserver
apps/jumpserver/middleware.py
.py
# ~*~ coding: utf-8 ~*~ import json import os import re import time from urllib.parse import urlparse, quote import pytz from django.conf import settings from django.core.exceptions import MiddlewareNotUsed from django.db.utils import OperationalError from django.http.response import HttpResponseForbidden, JsonRespon...
217
7,466
jumpserver
apps/jumpserver/wsgi.py
.py
""" WSGI config for jumpserver project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_S...
17
398
jumpserver
apps/jumpserver/utils.py
.py
# -*- coding: utf-8 -*- # from functools import partial from werkzeug.local import LocalProxy from common.local import thread_local def set_current_request(request): setattr(thread_local, 'current_request', request) def _find(attr): return getattr(thread_local, attr, None) def get_current_request(): ...
23
419
jumpserver
apps/jumpserver/asgi.py
.py
import os import django from channels.routing import get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "jumpserver.settings") django.setup() application = get_default_application()
9
205
jumpserver
apps/jumpserver/conf.py
.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # """ 配置分类: 1. Django使用的配置文件,写到settings中 2. 程序需要, 用户不需要更改的写到settings中 3. 程序需要, 用户需要更改的写到本config中 """ import base64 import copy import errno import json import logging import os import re import sys import types from importlib import import_module from urllib.parse import u...
1,206
43,328
jumpserver
apps/jumpserver/urls.py
.py
# ~*~ coding: utf-8 ~*~ from __future__ import unicode_literals import os import uuid import private_storage.urls from django.conf import settings from django.conf.urls.static import static from django.urls import path, include, re_path from django.views.i18n import JavaScriptCatalog from . import views, api resour...
115
4,829
jumpserver
apps/jumpserver/context_processor.py
.py
# -*- coding: utf-8 -*- # import datetime import os from django.conf import settings from django.templatetags.static import static from django.utils.translation import gettext_lazy as _ default_interface = dict(( ('logo_logout', static('img/logo.png')), ('logo_index', static('img/logo_text_white.png')), ('...
46
1,671
jumpserver
apps/jumpserver/const.py
.py
# -*- coding: utf-8 -*- # import os from .conf import ConfigManager __all__ = ['BASE_DIR', 'PROJECT_DIR', 'VERSION', 'CONFIG'] BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_DIR = os.path.dirname(BASE_DIR) VERSION = '2.0.0' CONFIG = ConfigManager.load_user_config()
15
303
jumpserver
apps/jumpserver/routing.py
.py
from channels.auth import AuthMiddlewareStack from channels.db import database_sync_to_async from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from django.core.handlers.asgi import ASGIRequest from django.conf import settings from authentication.backends.drf i...
114
3,415
jumpserver
apps/jumpserver/settings/logging.py
.py
# -*- coding: utf-8 -*- # import os from ..const import PROJECT_DIR, CONFIG LOG_DIR = os.path.join(PROJECT_DIR, 'data', 'logs') JUMPSERVER_LOG_FILE = os.path.join(LOG_DIR, 'jumpserver.log') DRF_EXCEPTION_LOG_FILE = os.path.join(LOG_DIR, 'drf_exception.log') UNEXPECTED_EXCEPTION_LOG_FILE = os.path.join(LOG_DIR, 'unexp...
145
4,300
jumpserver
apps/jumpserver/settings/custom.py
.py
# -*- coding: utf-8 -*- # from pathlib import Path from urllib.parse import quote from .base import TEMPLATES, STATIC_DIR from ..const import CONFIG # Storage settings COMMAND_STORAGE = { 'ENGINE': 'terminal.backends.command.db', } DEFAULT_TERMINAL_COMMAND_STORAGE = { "default": { "TYPE": "server", ...
334
14,475
jumpserver
apps/jumpserver/settings/libs.py
.py
# -*- coding: utf-8 -*- # import os import time from .base import ( REDIS_SSL_CA, REDIS_SSL_CERT, REDIS_SSL_KEY, REDIS_SSL_REQUIRED, REDIS_USE_SSL, REDIS_PROTOCOL, REDIS_SENTINEL_SERVICE_NAME, REDIS_SENTINELS, REDIS_SENTINEL_PASSWORD, REDIS_SENTINEL_SOCKET_TIMEOUT ) from ..const import CONFIG, PROJECT_DIR ...
259
9,580
jumpserver
apps/jumpserver/settings/auth.py
.py
# -*- coding: utf-8 -*- # import os import ldap from settings.ldap_tls import LDAPTLSUtil from ..const import CONFIG, PROJECT_DIR, BASE_DIR from . import exist_or_default # OTP settings OTP_ISSUER_NAME = CONFIG.OTP_ISSUER_NAME OTP_VALID_WINDOW = CONFIG.OTP_VALID_WINDOW OTP_DIGEST = CONFIG.OTP_DIGEST # Auth LDAP set...
386
17,429
jumpserver
apps/jumpserver/settings/_xpack.py
.py
# -*- coding: utf-8 -*- # import datetime import os from .base import INSTALLED_APPS, TEMPLATES from .. import const current_year = datetime.datetime.now().year corporation = f'FIT2CLOUD 飞致云 © 2014-{current_year}' XPACK_DIR = os.path.join(const.BASE_DIR, 'xpack') XPACK_DISABLED = os.environ.get('XPACK_ENABLED') in ...
37
1,115
jumpserver
apps/jumpserver/settings/base.py
.py
import os import re from django.urls import reverse_lazy from redis.sentinel import SentinelManagedSSLConnection from .. import const from ..const import CONFIG def exist_or_default(path, default): if not os.path.exists(path): path = default return path def parse_sentinels_host(sentinels_host): ...
491
16,811
jumpserver
apps/jumpserver/api/health.py
.py
import secrets import time from django.conf import settings from django.core.cache import cache from django.http.response import HttpResponse from rest_framework.permissions import AllowAny from rest_framework.response import Response from rest_framework.views import APIView from terminal.utils import ComponentsProme...
76
2,202
jumpserver
apps/jumpserver/api/dashboard.py
.py
from collections import defaultdict from django.core.cache import cache from django.db.models import Count, Max, F, CharField, Q from django.db.models.functions import Cast from django.http.response import JsonResponse from django.utils import timezone from django.utils.timesince import timesince from rest_framework.r...
496
17,913
jumpserver
apps/jumpserver/api/hostname.py
.py
from django.conf import settings from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework.permissions import AllowAny from common.permissions import OnlySuperUser # 此 api 返回 /etc/hostname 的值 # 在 DEBUG_DEV 配置下可以匿名访问 class HostnameView(...
27
869
jumpserver
apps/jumpserver/api/search.py
.py
import re from django.contrib.postgres.search import SearchVector from rest_framework.views import APIView from rest_framework.response import Response from django.conf import settings from django.db.models import Q from rest_framework.permissions import IsAuthenticated class GlobalSearchView(APIView): limits = ...
85
2,719
jumpserver
apps/jumpserver/api/aggregate/detail.py
.py
# views.py from drf_spectacular.utils import extend_schema, OpenApiParameter from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from .const import common_params from .proxy import ProxyMixin from .utils import param_dic_to_param one_param = [ { 'name': 'id', ...
76
2,424
jumpserver
apps/jumpserver/api/aggregate/list.py
.py
# views.py from drf_spectacular.utils import extend_schema from rest_framework.routers import DefaultRouter from rest_framework.views import APIView from .const import list_params, common_params from .proxy import ProxyMixin from .utils import param_dic_to_param router = DefaultRouter() BASE_URL = "http://localhost...
88
2,386
jumpserver
apps/jumpserver/api/aggregate/utils.py
.py
# views.py import re from functools import lru_cache from typing import Dict from django.urls import URLPattern from django.urls import URLResolver from drf_spectacular.utils import OpenApiParameter from rest_framework.routers import DefaultRouter router = DefaultRouter() BASE_URL = "http://localhost:8080" def cl...
129
4,136
jumpserver
apps/jumpserver/api/aggregate/__init__.py
.py
from .detail import ResourceDetailApi from .list import ResourceListApi from .supported import ResourceTypeListApi __all__ = [ 'ResourceListApi', 'ResourceDetailApi', 'ResourceTypeListApi', ]
10
205
jumpserver
apps/jumpserver/api/aggregate/proxy.py
.py
# views.py from urllib.parse import urlencode import requests from rest_framework.exceptions import NotFound, APIException from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.routers import DefaultRouter from rest_framework.views import APIView from...
76
2,469
jumpserver
apps/jumpserver/api/aggregate/supported.py
.py
# views.py from drf_spectacular.utils import extend_schema from rest_framework import serializers from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.routers import DefaultRouter from rest_framework.views import APIView from .utils import get_full_re...
46
1,441
jumpserver
apps/jumpserver/api/aggregate/const.py
.py
list_params = [ { "name": "search", "in": "query", "description": "A search term.", "required": False, "type": "string" }, { "name": "order", "in": "query", "description": "Which field to use when ordering the results.", "required": Fal...
58
2,035
jumpserver
apps/jumpserver/views/celery_flower.py
.py
# -*- coding: utf-8 -*- # from django.conf import settings from django.http import HttpResponse from django.utils.translation import gettext as _ from django.views.decorators.csrf import csrf_exempt from proxy.views import proxy_view flower_url = settings.FLOWER_URL __all__ = ['celery_flower_view'] @csrf_exempt def...
26
786
jumpserver
apps/jumpserver/views/swagger.py
.py
from drf_spectacular.views import ( SpectacularSwaggerView, SpectacularRedocView, SpectacularYAMLAPIView, SpectacularJSONAPIView ) from django.views.decorators.cache import cache_page from django.utils.decorators import method_decorator from rest_framework.response import Response from django.contrib.auth.mixi...
57
1,702
jumpserver
apps/jumpserver/views/index.py
.py
from django.views.generic import View from django.shortcuts import redirect from common.permissions import IsValidUser from common.views.mixins import PermissionsMixin __all__ = ['IndexView'] class IndexView(PermissionsMixin, View): permission_classes = [IsValidUser] def get(self, request, *args, **kwargs):...
14
353
jumpserver
apps/jumpserver/views/error_views.py
.py
# -*- coding: utf-8 -*- # from django.shortcuts import render from django.http import JsonResponse __all__ = ['handler404', 'handler500'] def handler404(request, *args, **argv): if request.content_type.find('application/json') > -1: response = JsonResponse({'error': 'Not found'}, status=404) else: ...
23
667
jumpserver
apps/jumpserver/views/schema.py
.py
import re from django.apps import apps from django.conf import settings from drf_spectacular.openapi import AutoSchema from drf_spectacular.generators import SchemaGenerator class CustomSchemaGenerator(SchemaGenerator): from_mcp = False def get_schema(self, request=None, public=False): self.from_mcp...
438
15,823
jumpserver
apps/jumpserver/views/other.py
.py
# -*- coding: utf-8 -*- # import os import re from urllib.parse import urlparse from django.conf import settings from django.http import HttpResponse from django.http import HttpResponseBadRequest from django.http import HttpResponseRedirect, JsonResponse from django.shortcuts import redirect from django.utils import ...
131
4,179
jumpserver
apps/jumpserver/rewriting/logging.py
.py
import os from logging.handlers import TimedRotatingFileHandler from datetime import datetime, timedelta class DailyTimedRotatingFileHandler(TimedRotatingFileHandler): def rotator(self, source, dest): """ Override the original method to rotate the log file daily.""" dest = self._get_rotate_dest_fi...
21
869
jumpserver
apps/jumpserver/rewriting/smtp.py
.py
import ssl from django.conf import settings from django.core.mail.backends.smtp import EmailBackend as BaseEmailBackend from django.utils.functional import cached_property class EmailBackend(BaseEmailBackend): @cached_property def ssl_context(self): context = super().ssl_context verify_mode =...
21
624
jumpserver
apps/jumpserver/rewriting/exchange.py
.py
import urllib3 from django.conf import settings from django.core.mail.backends.base import BaseEmailBackend from django.core.mail.message import sanitize_address from exchangelib import Account, Credentials, Configuration, DELEGATE from exchangelib import BaseProtocol, NoVerifyHTTPAdapter from exchangelib import Mailbo...
103
3,693
jumpserver
apps/jumpserver/rewriting/db.py
.py
import os import sys from django.db import models, transaction from django.db.transaction import atomic as db_atomic class ForeignKey(models.ForeignKey): def __init__(self, *args, **kwargs): kwargs['db_constraint'] = False super().__init__(*args, **kwargs) def atomic(using=None, savepoint=False...
38
1,011
jumpserver
apps/jumpserver/rewriting/pagination.py
.py
from django.conf import settings from django.core.exceptions import FieldError from rest_framework.pagination import LimitOffsetPagination class MaxLimitOffsetPagination(LimitOffsetPagination): max_limit = settings.MAX_PAGE_SIZE def get_count(self, queryset): try: return queryset.values_l...
22
785
jumpserver
apps/jumpserver/rewriting/storage/permissions.py
.py
# ~*~ coding: utf-8 ~*~ from django.conf import settings path_perms_map = { 'xpack': 'none', 'settings': 'none', 'img': 'none', 'replay': 'terminal.view_sessionreplay', 'applets': 'terminal.view_applet', 'virtual_apps': 'terminal.view_virtualapp', 'playbooks': 'ops.view_playbook', 'ima...
38
1,141
jumpserver
apps/jumpserver/rewriting/storage/servers.py
.py
from private_storage.servers import NginxXAccelRedirectServer, DjangoServer class StaticFileServer(object): @staticmethod def serve(private_file): full_path = private_file.full_path # todo: gzip 文件录像 nginx 处理后,浏览器无法正常解析内容 # 造成在线播放失败,暂时仅使用 nginx 处理 mp4 录像文件 if full_path.endswit...
15
540
jumpserver
apps/libs/process/ssh.py
.py
import logging import psutil from psutil import NoSuchProcess logger = logging.getLogger(__name__) def _should_kill(process): return process.pid != 1 and process.name() == 'ssh' def kill_ansible_ssh_process(pid): try: process = psutil.Process(pid) except NoSuchProcess as e: logger.erro...
27
609
jumpserver
apps/libs/ansible/modules_utils/ssh_tunnel.py
.py
import os import queue import socket import threading import time import paramiko import sshtunnel from sshtunnel import SSHTunnelForwarder class GatewayConnectTimeout(TimeoutError): pass class TimeoutSSHTunnelForwarder(SSHTunnelForwarder): """SSHTunnelForwarder with a bounded gateway start phase.""" ...
235
7,674
jumpserver
apps/libs/ansible/modules_utils/oracle_common.py
.py
import os import oracledb from oracledb.exceptions import DatabaseError from ansible.module_utils._text import to_native def oracle_common_argument_spec(): """ Returns a dict containing common options shared across the Oracle modules. """ options = dict( login_user=dict(type='str', required=...
110
3,802
jumpserver
apps/libs/ansible/modules_utils/mongodb_client.py
.py
from ansible_collections.community.mongodb.plugins.module_utils.mongodb_common import ( MongoClient, rename_ssl_option_for_pymongo4, ssl_connection_options, ) def _apply_connection_options(connection_params, module, tls_enabled): for item in module.params.get('connection_options') or []: if is...
72
2,494
jumpserver
apps/libs/ansible/modules_utils/remote_client.py
.py
import codecs import json import os import re import shlex import signal import sys import threading import time import traceback from functools import wraps import paramiko from libs.ansible.modules_utils.ssh_tunnel import TimeoutSSHTunnelForwarder DEFAULT_RE = '.*' SUDO_PROMPT_MARKER = '__JMS_SUDO_PROMPT__:' SUDO_...
1,221
44,940
jumpserver
apps/libs/ansible/modules/mongodb_user.py
.py
#!/usr/bin/python # Modified from ansible_collections.community.mongodb.plugins.modules.mongodb_user from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: mongodb_user short_description: Adds or removes a user from a MongoDB database description: -...
457
15,807
jumpserver
apps/libs/ansible/modules/mongodb_ping.py
.py
#!/usr/bin/python from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: mongodb_ping short_description: Check remote MongoDB server availability description: - Simple module to check remote MongoDB server availability. requirements: - "pymongo" ''' ...
159
4,117
jumpserver
apps/libs/ansible/modules/oracle_user.py
.py
#!/usr/bin/python from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: oracle_user short_description: Adds or removes a user from a Oracle database description: - Adds or removes a user from a Oracle database. options: authentication_type: d...
369
13,154
jumpserver
apps/libs/ansible/modules/ssh_ping.py
.py
#!/usr/bin/python from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: ssh_ping short_description: Use ssh to probe whether an asset is connectable description: - Use ssh to probe whether an asset is connectable. options: login_host: de...
167
5,032
jumpserver
apps/libs/ansible/modules/rdp_ping.py
.py
#!/usr/bin/python from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: custom_rdp_ping short_description: Use RDP to probe whether an asset is connectable. description: - Use RDP to probe whether an asset is connectable. options: login_host: ...
228
7,142
jumpserver
apps/libs/ansible/modules/custom_command.py
.py
#!/usr/bin/python from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: custom_command short_description: Adds or removes a user with custom commands by ssh description: - You can add or edit users using ssh with custom commands. options: protoc...
151
3,985
jumpserver
apps/libs/ansible/modules/oracle_ping.py
.py
#!/usr/bin/python from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: oracle_ping short_description: Check remote Oracle server availability description: - Simple module to check remote Oracle server availability. requirements: - "oracledb" ''' EX...
101
2,273
jumpserver
apps/libs/ansible/modules/postgresql_login_ping.py
.py
#!/usr/bin/python from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r''' --- module: postgresql_login_ping short_description: Verify PostgreSQL credentials with a minimal query description: - Connects with the supplied credentials and executes C(SELECT 1). option...
117
3,047
jumpserver
apps/libs/ansible/modules/telnet_ping.py
.py
#!/usr/bin/python from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: telnet_ping short_description: Use telnet to probe whether an asset is connectable description: - Use telnet to probe whether an asset is connectable ''' EXAMPLES = ''' - name:...
71
1,585
jumpserver
apps/libs/ansible/modules/mssql_script.py
.py
#!/usr/bin/python # Modified from ansible_collections.community.general.mssql_script from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = r""" module: mssql_script short_description: Execute SQL scripts on a MSSQL database version_added: "1.0.0" description: -...
419
13,392
jumpserver
apps/libs/ansible/modules/oracle_info.py
.py
#!/usr/bin/python from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r''' --- module: oracle_info short_description: Gather information about Oracle servers description: - Gathers information about Oracle servers. options: filter: description: - Limit the...
340
10,582
jumpserver
apps/labels/models.py
.py
from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import gettext_lazy as _ from common.utils import lazyproperty from orgs.mixins.models import JMSOrgBaseModel class Label(JMSOrgBaseMo...
53
1,710
jumpserver
apps/labels/apps.py
.py
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class LabelsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'labels' verbose_name = _('App Labels')
9
234
jumpserver
apps/labels/serializers.py
.py
from django.utils.translation import gettext_lazy as _ from rest_framework import serializers from common.serializers.fields import ObjectRelatedField, LabeledChoiceField from common.validators import ProjectUniqueValidator from orgs.mixins.serializers import BulkOrgResourceModelSerializer from .const import label_res...
84
3,004
jumpserver
apps/labels/urls.py
.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # from rest_framework_bulk.routes import BulkRouter from . import api app_name = 'labels' router = BulkRouter() router.register(r'labels', api.LabelViewSet, 'label') router.register(r'labels/(?P<label>.*)/resource-types/(?P<res_type>.*)/resources', api.L...
22
591
jumpserver
apps/labels/mixins.py
.py
from django.contrib.contenttypes.fields import GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from django.db.models import OneToOneField, Count from common.utils import lazyproperty from .models import LabeledResource __all__ = ['LabeledMixin'] class LabeledM...
78
2,548
jumpserver
apps/labels/api.py
.py
from django.core.exceptions import ValidationError from django.shortcuts import get_object_or_404 from django.utils.translation import gettext_lazy as _ from rest_framework import status from rest_framework.decorators import action from rest_framework.response import Response from common.api.generic import JMSModelVie...
182
6,558
jumpserver
apps/labels/const.py
.py
from django.utils.functional import LazyObject class LabeledResourceType(LazyObject): @staticmethod def get_res_types(): from rbac.models import ContentType from .mixins import LabeledMixin content_types = ContentType.objects.all() ids = [] for ct in content_types: ...
26
732
jumpserver
apps/assets/notifications.py
.py
from django.utils.translation import gettext as _ from notifications.notifications import UserMessage class BulkUpdatePlatformSkipAssetUserMsg(UserMessage): def __init__(self, user, assets): super().__init__(user) self.assets = assets def get_html_msg(self) -> dict: subject = _("Batc...
26
810
jumpserver
apps/assets/exceptions.py
.py
from django.utils.translation import gettext_lazy as _ from rest_framework import status from common.exceptions import JMSException class NodeIsBeingUpdatedByOthers(JMSException): status_code = status.HTTP_409_CONFLICT class NotSupportedTemporarilyError(JMSException): default_detail = _("This function is n...
13
347
jumpserver
apps/assets/apps.py
.py
from __future__ import unicode_literals from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class AssetsConfig(AppConfig): name = 'assets' verbose_name = _('App Assets') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def ready(sel...
20
517
jumpserver
apps/assets/filters.py
.py
# -*- coding: utf-8 -*- # from django.db.models import Q from rest_framework import filters from rest_framework.compat import coreapi, coreschema from assets.utils import get_node_from_request, is_query_node_all_assets class AssetByNodeFilterBackend(filters.BaseFilterBackend): fields = ['node', 'all'] def g...
92
2,870
jumpserver
apps/assets/locks.py
.py
from orgs.utils import current_org from common.utils.lock import DistributedLock from assets.models import Node class NodeTreeUpdateLock(DistributedLock): name_template = 'assets.node.tree.update.<org_id:{org_id}>' def get_name(self): if current_org: org_id = current_org.id else: ...
30
886
jumpserver
apps/assets/hands.py
.py
""" jumpserver.__app__.hands.py ~~~~~~~~~~~~~~~~~ This app depends other apps api, function .. should be import or write mack here. Other module of this app shouldn't connect with other app. :copyright: (c) 2014-2018 by JumpServer Team. :license: GPL v2, see LICENSE for more details. """ fr...
15
359
jumpserver
apps/assets/pagination.py
.py
from rest_framework.pagination import LimitOffsetPagination from rest_framework.request import Request from assets.models import Node from common.utils import get_logger logger = get_logger(__name__) class AssetPaginationBase(LimitOffsetPagination): _request = None _view = None _user = None def ini...
58
2,017
jumpserver
apps/assets/urls/api_urls.py
.py
# coding:utf-8 from django.urls import path from rest_framework_bulk.routes import BulkRouter from labels.api import LabelViewSet from .. import api app_name = 'assets' router = BulkRouter() router.register(r'categories', api.CategoryViewSet, 'category') router.register(r'assets', api.AssetViewSet, 'asset') router.r...
61
3,567
jumpserver
apps/assets/urls/views_urls.py
.py
# coding:utf-8 app_name = 'assets' urlpatterns = [ ]
7
55
jumpserver
apps/assets/serializers/gateway.py
.py
# -*- coding: utf-8 -*- # from django.utils.translation import gettext_lazy as _ from rest_framework import serializers from .asset.common import AccountSecretSerializer from .asset.host import HostSerializer from ..models import Gateway, Asset __all__ = ['GatewaySerializer', 'GatewayWithAccountSecretSerializer'] c...
37
1,197
jumpserver
apps/assets/serializers/favorite_asset.py
.py
# -*- coding: utf-8 -*- # from rest_framework import serializers from common.serializers import BulkSerializerMixin from ..models import FavoriteAsset, FavoriteFolder __all__ = ['FavoriteAssetSerializer', 'FavoriteFolderSerializer'] class FavoriteFolderSerializer(BulkSerializerMixin, serializers.ModelSerializer): ...
61
1,829
jumpserver
apps/assets/serializers/domain.py
.py
# -*- coding: utf-8 -*- # from django.utils.translation import gettext_lazy as _ from rest_framework import serializers from common.serializers import ResourceLabelsMixin from common.serializers.fields import ObjectRelatedField from orgs.mixins.serializers import BulkOrgResourceModelSerializer from .gateway import Gat...
75
2,879
jumpserver
apps/assets/serializers/platform.py
.py
from django.db.models import QuerySet from django.utils.translation import gettext_lazy as _ from rest_framework import serializers from rest_framework.validators import UniqueValidator from assets.models import Asset from common.serializers import ( WritableNestedModelSerializer, type_field_map, MethodSerializer,...
293
12,166
jumpserver
apps/assets/serializers/my_asset.py
.py
# -*- coding: utf-8 -*- # from rest_framework import serializers from django.utils.translation import gettext_lazy as _ from ..models import MyAsset __all__ = ['MyAssetSerializer'] class MyAssetSerializer(serializers.ModelSerializer): user = serializers.HiddenField( default=serializers.CurrentUserDefau...
39
1,237
jumpserver
apps/assets/serializers/cagegory.py
.py
from django.utils.translation import gettext_lazy as _ from rest_framework import serializers __all__ = [ 'TypeSerializer', 'CategorySerializer', 'ProtocolSerializer' ] class TypeSerializer(serializers.Serializer): label = serializers.CharField(max_length=64, required=False, allow_blank=True, label=_('Label'...
25
1,224
jumpserver
apps/assets/serializers/node.py
.py
# -*- coding: utf-8 -*- from django.utils.translation import gettext as _ from rest_framework import serializers from orgs.mixins.serializers import BulkOrgResourceModelSerializer from ..models import Asset, Node __all__ = [ 'NodeSerializer', "NodeAddChildrenSerializer", "NodeAssetsSerializer", "NodeTaskSeria...
82
2,564
jumpserver
apps/assets/serializers/automations/base.py
.py
from django.utils.translation import gettext_lazy as _ from rest_framework import serializers from assets.models import Asset, Node, BaseAutomation, AutomationExecution from common.const.choices import Trigger, Status from common.serializers.fields import ObjectRelatedField, LabeledChoiceField from common.utils import...
92
3,507
jumpserver
apps/assets/serializers/asset/web.py
.py
from assets.models import Web from .common import AssetSerializer __all__ = ['WebSerializer'] class WebSerializer(AssetSerializer): class Meta(AssetSerializer.Meta): model = Web fields = AssetSerializer.Meta.fields + [ 'autofill', 'username_selector', 'password_selector', ...
39
1,070
jumpserver
apps/assets/serializers/asset/device.py
.py
from assets.models import Device from .common import AssetSerializer __all__ = ['DeviceSerializer'] class DeviceSerializer(AssetSerializer): class Meta(AssetSerializer.Meta): model = Device
11
206
jumpserver
apps/assets/serializers/asset/cloud.py
.py
from assets.models import Cloud from .common import AssetSerializer __all__ = ['CloudSerializer'] class CloudSerializer(AssetSerializer): class Meta(AssetSerializer.Meta): model = Cloud fields = AssetSerializer.Meta.fields extra_kwargs = { **AssetSerializer.Meta.extra_kwargs, ...
17
400
jumpserver
apps/assets/serializers/asset/custom.py
.py
from django.db.models import QuerySet from django.utils.translation import gettext_lazy as _, get_language from assets.models import Custom, Platform, Asset from common.const import UUID_PATTERN from common.serializers import create_serializer_class from common.serializers.common import DictSerializer, MethodSerialize...
87
3,086
jumpserver
apps/assets/serializers/asset/ds.py
.py
from django.utils.translation import gettext_lazy as _ from assets.models import DirectoryService from .common import AssetSerializer __all__ = ['DSSerializer'] class DSSerializer(AssetSerializer): class Meta(AssetSerializer.Meta): model = DirectoryService fields = AssetSerializer.Meta.fields + ...
23
738
jumpserver
apps/assets/serializers/asset/database.py
.py
from django.db.models import QuerySet from django.utils.translation import gettext_lazy as _ from rest_framework import serializers from assets.models import Database, Platform from assets.serializers.gateway import GatewayWithAccountSecretSerializer from .common import AssetSerializer __all__ = ['DatabaseSerializer'...
76
2,703
jumpserver
apps/assets/serializers/asset/host.py
.py
from django.utils.translation import gettext_lazy as _ from assets.models import Host from .common import AssetSerializer from .info.gathered import HostGatheredInfoSerializer __all__ = ['HostSerializer'] class HostSerializer(AssetSerializer): gathered_info = HostGatheredInfoSerializer(required=False, read_only...
22
640
jumpserver
apps/assets/serializers/asset/common.py
.py
# -*- coding: utf-8 -*- # from django.db.models import F, Q from django.db.transaction import atomic from django.utils.translation import gettext_lazy as _ from rest_framework import serializers from accounts.models import Account from accounts.serializers import AccountSerializer from common.const import UUID_PATTER...
589
22,257
jumpserver
apps/assets/serializers/asset/gpt.py
.py
from django.utils.translation import gettext_lazy as _ from rest_framework import serializers from assets.models import GPT from .common import AssetSerializer __all__ = ['GPTSerializer'] class GPTSerializer(AssetSerializer): class Meta(AssetSerializer.Meta): model = GPT fields = AssetSerializer...
34
1,013
jumpserver
apps/assets/serializers/asset/info/gathered.py
.py
from django.utils.translation import gettext_lazy as _ from rest_framework import serializers class HostGatheredInfoSerializer(serializers.Serializer): vendor = serializers.CharField(max_length=64, required=False, allow_blank=True, label=_('Vendor')) model = serializers.CharField(max_length=54, required=False...
32
1,804
jumpserver
apps/assets/serializers/asset/info/spec.py
.py
from django.utils.translation import gettext_lazy as _ from rest_framework import serializers from assets.const import FillType from assets.models import Database, Web, DirectoryService from common.serializers.fields import LabeledChoiceField class DatabaseSpecSerializer(serializers.ModelSerializer): class Meta:...
65
1,921
jumpserver
apps/assets/automations/methods.py
.py
import json import os from functools import partial from common.utils.yml import yaml_load_with_i18n def is_ignored_pkg_path(path): parts = os.path.normpath(path).split(os.sep) for part in parts: if not part: continue if part == '__MACOSX' or part.startswith('._'): ret...
95
3,141
jumpserver
apps/assets/automations/endpoint.py
.py
from .gather_facts.manager import GatherFactsManager from .ping.manager import PingManager from .ping_gateway.manager import PingGatewayManager from ..const import AutomationTypes class ExecutionManager: manager_type_mapper = { AutomationTypes.ping: PingManager, AutomationTypes.ping_gateway: PingG...
23
716
jumpserver
apps/assets/automations/base/manager.py
.py
import hashlib import json import logging import os import re import shutil import time from collections import defaultdict from socket import gethostname import yaml from celery import current_task from celery.worker import state as celery_worker_state from django.conf import settings from django.template.loader impo...
1,482
55,953
jumpserver
apps/assets/automations/gather_facts/manager.py
.py
from assets.const import AutomationTypes from common.utils import get_logger from .format_asset_info import FormatAssetInfo from ..base.manager import BasePlaybookManager logger = get_logger(__name__) class GatherFactsManager(BasePlaybookManager): def __init__(self, *args, **kwargs): super().__init__(*ar...
62
2,162
jumpserver
apps/assets/automations/gather_facts/format_asset_info.py
.py
from collections import Counter from django.utils.translation import gettext as _ __all__ = ['FormatAssetInfo'] class FormatAssetInfo: def __init__(self, tp): self.tp = tp @staticmethod def get_cpu_model_count(cpus): try: if len(cpus) % 3 == 0: step = 3 ...
73
2,204