Jumpserver是全球首款完全开源的堡垒机,是符合 4A 的专业运维审计系统。 http://www.jumpserver.org
jms很好用,但是引入公司内部,也会有一些问题,比如资产导入,资产和项目关联,如何和现有cmdb打通等问题。我这里只是抛砖引玉,介绍下jms如何二次开发,做企业定制化版的jumpserver,打通DevOps系统的方法。
首先,以增加项目管理 这个功能为例,说说堡垒机如何二次开发的。
基于版本 Version 1.4.10-2 GPLv2.
一、概述
Jumpserver用的是python的django框架开发,API 采用了DRF(Django REST framework),基于CBV(Class-based views)开发模式,因此,二次开发也是比较简单的,一般先定义model,然后写api,再使用template渲染,前端基本用datatables较多。
实现效果:
二、实战
项目(project)管理或者说是服务(service)管理,服务和主机是有关系的,我这里一个主机可以部署多个服务,同时一个服务也可以部署在多台主机上,所以是多堆多的关系
2.1 定义project model
jumpserver/apps/assets/models/project.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
import logging
from django.utils.translation import ugettext_lazy as _
import uuid
from django.core.cache import cache
__all__ = ['Project', 'TYPE_CHOICES']
logger = logging.getLogger(__name__)
TYPE_CHOICES = (
('Java', 'java'),
('React', 'react'),
('Cpp', 'c++'),
('Python', 'python'),
('Middleware', 'Middleware'),
('Other', 'Other'),
)
class Project(models.Model):
TYPE_CHOICES =TYPE_CHOICES
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
name = models.CharField(max_length=64, unique=True, verbose_name=_('Name'))
parent = models.ForeignKey('self', null=True, blank=True, related_name="children", on_delete=models.SET_NULL)
domain_name = models.CharField(max_length=64, blank=True, verbose_name=_('Domain Name'))
git_address = models.CharField(max_length=128, blank=True, verbose_name=_('Git Address'))
port = models.IntegerField(blank=True, null=True, verbose_name=_('Open port'))
type = models.CharField(choices=TYPE_CHOICES, max_length=16, blank=True, null=True,
default='Java', verbose_name=_('Project type'), )
dev_users = models.ManyToManyField(
'users.User', related_name='users1',
blank=True, verbose_name=_('Dev Users')
)
sa_users = models.ManyToManyField(
'users.User', related_name='users2',
blank=True, verbose_name=_('Sa Users')
)
scrum_master = models.ForeignKey('users.User', on_delete=models.SET_NULL, null=True, verbose_name=_('Scrum Master'))
created_by = models.CharField(max_length=32, blank=True, verbose_name=_('Created by'))
updated_by = models.CharField(max_length=32, blank=True, verbose_name=_('Updated by'))
date_created = models.DateTimeField(auto_now_add=True, null=True, verbose_name=_('Date created'))
date_updated = models.DateTimeField(auto_now=True, null=True, verbose_name=_('Date updated'))
comment = models.TextField(blank=True, verbose_name=_('Comment'))
level = models.IntegerField(default=0, verbose_name=_('Level'))
def __unicode__(self):
return self.name
__str__ = __unicode__
@property
def all_sa_users(self):
return [user.name for user in self.sa_users.all()]
@property
def all_dev_users(self):
return [user.name for user in self.dev_users.all()]
def get_related_assets(self):
assets = self.assets.all()
return assets
def get_related_assets_ip(self):
assets = self.assets.all()
return [{'ip': asset.ip, 'environment': asset.environment} for asset in assets]
@property
def all_assets_ip(self):
return self.get_related_assets_ip()
class Meta:
ordering = ['name']
2.2 修改asset model
jumpserver/apps/assets/models/asset.py
# 增加环境定义
ENV_CHOICES = (
('DEV', 'dev'),
('TEST', 'test'),
('DEMO', 'demo'),
('TDEMO', 'tdemo'),
('PROD', 'prod'),
('Other', 'other'),
)
environment = models.CharField(max_length=32, choices=ENV_CHOICES, default='DEV', verbose_name=_('Environment'))
# Project 和 asset 多对多关系
projects = models.ManyToManyField(Project, blank=True, verbose_name=_('Projects'), related_name='assets', )
2.3 加入全局变量中init
jumpserver/apps/assets/models/init.py 末尾增加
from .project import *
2.4 定义DRF的serializers
jumpserver/apps/assets/serializers/project.py
from rest_framework_bulk import BulkListSerializer, BulkSerializerMixin
from rest_framework import serializers
from ..models import Project, Asset
class ProjectSerializer(serializers.ModelSerializer):
asset_count = serializers.SerializerMethodField()
class Meta:
model = Project
fields = '__all__'
@staticmethod
def get_asset_count(obj):
return obj.assets.count()
class ProjectAssetsSerializer(serializers.ModelSerializer):
class Meta:
fields = ['id', 'name', 'port']
model = Project
def get_field_names(self, declared_fields, info):
fields = super().get_field_names(declared_fields, info)
fields.extend([
'all_assets_ip'
])
return fields
class ProjectUpdateSerializer(serializers.ModelSerializer):
"""update the project, and add or delete the asset to the project"""
assets = serializers.PrimaryKeyRelatedField(many=True, queryset=Asset.objects.all())
class Meta:
model = Project
fields = ['id', 'assets']
class AssetUpdateProjectSerializer(serializers.ModelSerializer):
projects = serializers.PrimaryKeyRelatedField(many=True, queryset=Project.objects.all())
class Meta:
model = Asset
fields = ['id', 'projects']
2.5 增加URl支持
/jumpserver/apps/assets/urls/api_urls.py
router.register(r'projects', api.ProjectViewSet, 'project')
router.register(r'projects-assets', api.ProjectAssetsViewSet, 'project-assets-view')
# urlpatterns 增加:
path(r'assets//projects/',
api.AssetUpdateProjectApi.as_view(), name='asset-update-project'),
path(r'projects//assets/',
api.ProjectUpdateApi.as_view(), name='project-update-assets'),
path('project//assets/',
api.ProjectAssetsListView.as_view(), name='project-assets'),
API到这里基本写完了,至于前端的一些,都是调用这些api,进行增删改查操作,详情见github
3 数据库迁移
定义了模型以后,需要执行migrate命令进行数据库变更,省了自己执行sql
cd jumpserver/utils
bash make_migrations.sh
4 国际化
因为我们定义的好多变量都是英文的,这里可以通过国际化手段支持中英文
# 先执行
cd jumpserver/apps
python manage.py makemessages -l zh
# 修改jumpserver/apps/locale/zh/LC_MESSAGES/django.po 的中英文对应
vim jumpserver/apps/locale/zh/LC_MESSAGES/django.po
# 修改完成后生效,完全生效需要服务重启
python manage.py compilemessages
完全代码请看:
https://github.com/getway/jumpserver/commit/eb1507a018766cbd5d717e4af64ac2a8b511e25c
更多:
https://oneops.top/2019/08/15/jumpserver%E4%BA%8C%E6%AC%A1%E5%BC%80%E5%8F%91%E4%B8%80%EF%BC%9A%E5%A2%9E%E5%8A%A0%E9%A1%B9%E7%9B%AE%E7%AE%A1%E7%90%86/