pull/26/head
liuzheng712 2015-10-04 00:53:01 +08:00
parent 11b3cee346
commit 5a5928483f
10 changed files with 90 additions and 167 deletions

View File

@ -1,10 +1,28 @@
- model: IDC.person - model: juser.user
pk: 5000
fields:
username: admin
name: admin
password: pbkdf2_sha256$20000$jBIDGPB2j5JT$orxqGgzzjzykColYm1BswPjgHOiERjZkcgkuVIkD2Hc=
email: admin@jumpserver.org
role: SU
is_active: 1
- model: juser.user
pk: 5001
fields:
username: group_admin
name: group_admin
password: pbkdf2_sha256$20000$ttObUWd15q10$NJoyZf2OZz9oiw2g4j2TkTh9zGgyVDRFdUkhn8X0nB0=
email: group_admin@jumpserver.org
role: DA
is_active: 1
- model: juser.usergroup
pk: 1 pk: 1
fields: fields:
first_name: John name: ALL
last_name: Lennon comment: ALL
- model: myapp.person - model: juser.usergroup
pk: 2 pk: 2
fields: fields:
first_name: Paul name: 默认
last_name: McCartney comment: 默认

View File

@ -65,7 +65,7 @@ class Asset(models.Model):
username = models.CharField(max_length=20, blank=True, null=True) username = models.CharField(max_length=20, blank=True, null=True)
password = models.CharField(max_length=80, blank=True, null=True) password = models.CharField(max_length=80, blank=True, null=True)
use_default_auth = models.BooleanField(default=True) use_default_auth = models.BooleanField(default=True)
date_added = models.DateTimeField(auto_now=True, default=datetime.datetime.now(), null=True) date_added = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True) is_active = models.BooleanField(default=True)
comment = models.CharField(max_length=100, blank=True, null=True) comment = models.CharField(max_length=100, blank=True, null=True)

View File

@ -6,10 +6,8 @@ from django.shortcuts import render_to_response
from jumpserver.api import * from jumpserver.api import *
from jasset.views import httperror from jasset.views import httperror
from django.http import HttpResponseNotFound from django.http import HttpResponseNotFound
from models import Log
CONF = ConfigParser() from jumpserver.settings import web_socket_host
CONF.read('%s/jumpserver.conf' % BASE_DIR)
def get_user_info(request, offset): def get_user_info(request, offset):
""" 获取用户信息及环境 """ """ 获取用户信息及环境 """
@ -58,7 +56,6 @@ def log_list(request, offset):
""" 显示日志 """ """ 显示日志 """
header_title, path1, path2 = u'查看日志', u'查看日志', u'在线用户' header_title, path1, path2 = u'查看日志', u'查看日志', u'在线用户'
keyword = request.GET.get('keyword', '') keyword = request.GET.get('keyword', '')
web_socket_host = CONF.get('websocket', 'web_socket_host')
posts = get_user_log(get_user_info(request, offset)) posts = get_user_log(get_user_info(request, offset))
contact_list, p, contacts, page_range, current_page, show_first, show_end = pages(posts, request) contact_list, p, contacts, page_range, current_page, show_first, show_end = pages(posts, request)

View File

@ -1,8 +1,6 @@
# coding: utf-8 # coding: utf-8
import os, sys, time import os, sys, time
from ConfigParser import ConfigParser
import getpass
from Crypto.Cipher import AES from Crypto.Cipher import AES
import crypt import crypt
from binascii import b2a_hex, a2b_hex from binascii import b2a_hex, a2b_hex
@ -11,14 +9,15 @@ import datetime
import random import random
import subprocess import subprocess
import paramiko import paramiko
import struct, fcntl, signal,socket, select, fnmatch import struct, fcntl, signal, socket, select, fnmatch
from settings import JLOG_FILE, KEY, URL, log_dir, log_level
from django.core.paginator import Paginator, EmptyPage, InvalidPage from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.http import HttpResponse, Http404 from django.http import HttpResponse, Http404
from django.template import RequestContext from django.template import RequestContext
from juser.models import User, UserGroup from juser.models import User, UserGroup
from jasset.models import Asset, AssetGroup from jasset.models import Asset, AssetGroup
from jlog.models import Log # from jlog.models import Log
from jasset.models import AssetAlias from jasset.models import AssetAlias
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from django.http import HttpResponseRedirect from django.http import HttpResponseRedirect
@ -36,22 +35,6 @@ except ImportError:
sys.exit() sys.exit()
BASE_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
CONF = ConfigParser()
CONF.read(os.path.join(BASE_DIR, 'jumpserver.conf'))
LOG_DIR = os.path.join(BASE_DIR, 'logs')
JLOG_FILE = os.path.join(LOG_DIR, 'jumpserver.log')
SSH_KEY_DIR = os.path.join(BASE_DIR, 'keys')
# SERVER_KEY_DIR = os.path.join(SSH_KEY_DIR, 'server')
KEY = CONF.get('base', 'key')
LOGIN_NAME = getpass.getuser()
# LDAP_ENABLE = CONF.getint('ldap', 'ldap_enable')
URL = CONF.get('base', 'url')
MAIL_ENABLE = CONF.get('mail', 'mail_enable')
MAIL_FROM = CONF.get('mail', 'email_host_user')
log_dir = os.path.join(BASE_DIR, 'logs')
def set_log(level): def set_log(level):
""" """
return a log file object return a log file object
@ -146,7 +129,7 @@ def page_list_return(total, current=1):
min_page = current - 2 if current - 4 > 0 else 1 min_page = current - 2 if current - 4 > 0 else 1
max_page = min_page + 4 if min_page + 4 < total else total max_page = min_page + 4 if min_page + 4 < total else total
return range(min_page, max_page+1) return range(min_page, max_page + 1)
def pages(post_objects, request): def pages(post_objects, request):
@ -186,6 +169,7 @@ class Jtty(object):
A virtual tty class A virtual tty class
一个虚拟终端类实现连接ssh和记录日志 一个虚拟终端类实现连接ssh和记录日志
""" """
def __init__(self, user, asset): def __init__(self, user, asset):
self.chan = None self.chan = None
self.username = user.username self.username = user.username
@ -404,7 +388,7 @@ class PyCrypt(object):
symbol = '!@$%^&*()_' symbol = '!@$%^&*()_'
salt_list = [] salt_list = []
if especial: if especial:
for i in range(length-4): for i in range(length - 4):
salt_list.append(random.choice(salt_key)) salt_list.append(random.choice(salt_key))
for i in range(4): for i in range(4):
salt_list.append(random.choice(symbol)) salt_list.append(random.choice(symbol))
@ -489,6 +473,7 @@ def require_role(role='user'):
decorator for require user role in ["super", "admin", "user"] decorator for require user role in ["super", "admin", "user"]
要求用户是某种角色 ["super", "admin", "user"]的装饰器 要求用户是某种角色 ["super", "admin", "user"]的装饰器
""" """
def _deco(func): def _deco(func):
def __deco(request, *args, **kwargs): def __deco(request, *args, **kwargs):
if role == 'user': if role == 'user':
@ -501,7 +486,9 @@ def require_role(role='user'):
if request.session.get('role_id', 0) < 2: if request.session.get('role_id', 0) < 2:
return HttpResponseRedirect('/') return HttpResponseRedirect('/')
return func(request, *args, **kwargs) return func(request, *args, **kwargs)
return __deco return __deco
return _deco return _deco
@ -584,7 +571,7 @@ def validate(request, user_group=None, user=None, asset_group=None, asset=None,
if edept: if edept:
if dept.id != int(edept[0]): if dept.id != int(edept[0]):
return False return False
if user_group: if user_group:
dept_user_groups = dept.usergroup_set.all() dept_user_groups = dept.usergroup_set.all()
user_group_ids = [] user_group_ids = []
@ -710,6 +697,4 @@ CRYPTOR = PyCrypt(KEY)
# ldap_conn = LDAPMgmt(LDAP_HOST_URL, LDAP_BASE_DN, LDAP_ROOT_DN, LDAP_ROOT_PW) # ldap_conn = LDAPMgmt(LDAP_HOST_URL, LDAP_BASE_DN, LDAP_ROOT_DN, LDAP_ROOT_PW)
# else: # else:
# ldap_conn = None # ldap_conn = None
logger = set_log(log_level)
log_level = CONF.get('base', 'log')
logger = set_log(log_level)

View File

@ -11,6 +11,7 @@ https://docs.djangoproject.com/en/1.7/ref/settings/
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os import os
import ConfigParser import ConfigParser
import getpass
config = ConfigParser.ConfigParser() config = ConfigParser.ConfigParser()
@ -22,7 +23,7 @@ DB_PORT = config.getint('db', 'port')
DB_USER = config.get('db', 'user') DB_USER = config.get('db', 'user')
DB_PASSWORD = config.get('db', 'password') DB_PASSWORD = config.get('db', 'password')
DB_DATABASE = config.get('db', 'database') DB_DATABASE = config.get('db', 'database')
AUTH_USER_MODEL = 'juser.CustomUser' AUTH_USER_MODEL = 'juser.User'
# mail config # mail config
EMAIL_HOST = config.get('mail', 'email_host') EMAIL_HOST = config.get('mail', 'email_host')
EMAIL_PORT = config.get('mail', 'email_port') EMAIL_PORT = config.get('mail', 'email_port')
@ -30,6 +31,24 @@ EMAIL_HOST_USER = config.get('mail', 'email_host_user')
EMAIL_HOST_PASSWORD = config.get('mail', 'email_host_password') EMAIL_HOST_PASSWORD = config.get('mail', 'email_host_password')
EMAIL_USE_TLS = config.getboolean('mail', 'email_use_tls') EMAIL_USE_TLS = config.getboolean('mail', 'email_use_tls')
# ======== Log ==========
LOG = False
LOG_DIR = os.path.join(BASE_DIR, 'logs')
JLOG_FILE = os.path.join(LOG_DIR, 'jumpserver.log')
SSH_KEY_DIR = os.path.join(BASE_DIR, 'keys')
# SERVER_KEY_DIR = os.path.join(SSH_KEY_DIR, 'server')
KEY = config.get('base', 'key')
LOGIN_NAME = getpass.getuser()
# LDAP_ENABLE = CONF.getint('ldap', 'ldap_enable')
URL = config.get('base', 'url')
MAIL_ENABLE = config.get('mail', 'mail_enable')
MAIL_FROM = config.get('mail', 'email_host_user')
log_dir = os.path.join(BASE_DIR, 'logs')
log_level = config.get('base', 'log')
web_socket_host = config.get('websocket', 'web_socket_host')
# Quick-start development settings - unsuitable for production # Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
@ -64,9 +83,9 @@ INSTALLED_APPS = (
MIDDLEWARE_CLASSES = ( MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware', 'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',
#'django.contrib.auth.middleware.SessionAuthenticationMiddleware', # 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',
) )
@ -79,17 +98,23 @@ WSGI_APPLICATION = 'jumpserver.wsgi.application'
# Database # Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases # https://docs.djangoproject.com/en/1.7/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.mysql',
# 'NAME': DB_DATABASE,
# 'USER': DB_USER,
# 'PASSWORD': DB_PASSWORD,
# 'HOST': DB_HOST,
# 'PORT': DB_PORT,
# }
# }
DATABASES = { DATABASES = {
'default': { 'default': {
'ENGINE': 'django.db.backends.mysql', 'ENGINE': 'django.db.backends.sqlite3',
'NAME': DB_DATABASE, 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'USER': DB_USER,
'PASSWORD': DB_PASSWORD,
'HOST': DB_HOST,
'PORT': DB_PORT,
} }
} }
TEMPLATE_CONTEXT_PROCESSORS = ( TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth', 'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug', 'django.core.context_processors.debug',
@ -105,7 +130,7 @@ TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'templates'),
) )
#STATIC_ROOT = os.path.join(BASE_DIR, 'static') # STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = ( STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"), os.path.join(BASE_DIR, "static"),
@ -128,5 +153,3 @@ USE_TZ = False
# https://docs.djangoproject.com/en/1.7/howto/static-files/ # https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/' STATIC_URL = '/static/'

View File

@ -14,7 +14,7 @@ import paramiko
from jumpserver.api import * from jumpserver.api import *
from django.contrib.auth import authenticate, login, logout from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required
from settings import BASE_DIR
def getDaysByNum(num): def getDaysByNum(num):
today = datetime.date.today() today = datetime.date.today()

View File

@ -21,7 +21,7 @@ class UserGroup(models.Model):
from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser): class User(AbstractUser):
USER_ROLE_CHOICES = ( USER_ROLE_CHOICES = (
('SU', 'SuperUser'), ('SU', 'SuperUser'),
('GA', 'GroupAdmin'), ('GA', 'GroupAdmin'),
@ -34,113 +34,6 @@ class CustomUser(AbstractUser):
ssh_key_pwd = models.CharField(max_length=200) ssh_key_pwd = models.CharField(max_length=200)
class User(models.Model):
USER_ROLE_CHOICES = (
('SU', 'SuperUser'),
('GA', 'GroupAdmin'),
('CU', 'CommonUser'),
)
username = models.CharField(max_length=80, unique=True)
password = models.CharField(max_length=100)
name = models.CharField(max_length=80)
email = models.EmailField(max_length=75)
role = models.CharField(max_length=2, choices=USER_ROLE_CHOICES, default='CU')
uuid = models.CharField(max_length=100)
group = models.ManyToManyField(UserGroup)
ssh_key_pwd = models.CharField(max_length=200)
is_active = models.BooleanField(default=True)
last_login = models.DateTimeField(null=True)
date_joined = models.DateTimeField(null=True)
def __unicode__(self):
return self.username
def get_asset_group(self):
"""
Get user host_groups.
获取用户有权限的主机组
"""
host_group_list = []
perm_list = []
user_group_all = self.group.all()
for user_group in user_group_all:
perm_list.extend(user_group.perm_set.all())
for perm in perm_list:
host_group_list.append(perm.asset_group)
return host_group_list
def get_asset_group_info(self, printable=False):
"""
Get or print asset group info
获取或打印用户授权资产组
"""
asset_groups_info = {}
asset_groups = self.get_asset_group()
for asset_group in asset_groups:
asset_groups_info[asset_group.id] = [asset_group.name, asset_group.comment]
if printable:
for group_id in asset_groups_info:
if asset_groups_info[group_id][1]:
print "[%3s] %s -- %s" % (group_id,
asset_groups_info[group_id][0],
asset_groups_info[group_id][1])
else:
print "[%3s] %s" % (group_id, asset_groups_info[group_id][0])
print ''
else:
return asset_groups_info
def get_asset(self):
"""
Get the assets of under the user control.
获取主机列表
"""
assets = []
asset_groups = self.get_asset_group()
for asset_group in asset_groups:
assets.extend(asset_group.asset_set.all())
return assets
def get_asset_info(self, printable=False):
"""
Get or print the user asset info
获取或打印用户资产信息
"""
from jasset.models import AssetAlias
assets_info = {}
assets = self.get_asset()
for asset in assets:
asset_alias = AssetAlias.objects.filter(user=self, asset=asset)
if asset_alias and asset_alias[0].alias != '':
assets_info[asset.ip] = [asset.id, asset.ip, str(asset_alias[0].alias)]
else:
assets_info[asset.ip] = [asset.id, asset.ip, str(asset.comment)]
if printable:
ips = assets_info.keys()
ips.sort()
for ip in ips:
if assets_info[ip][2]:
print '%-15s -- %s' % (ip, assets_info[ip][2])
else:
print '%-15s' % ip
print ''
else:
return assets_info
def update(self, **kwargs):
for key, value in kwargs.items():
self.__setattr__(key, value)
self.save()
class AdminGroup(models.Model): class AdminGroup(models.Model):
""" """
under the user control group under the user control group

View File

@ -59,6 +59,7 @@ def db_add_user(**kwargs):
admin_groups = kwargs.pop('admin_groups') admin_groups = kwargs.pop('admin_groups')
role = kwargs.get('role', 'CU') role = kwargs.get('role', 'CU')
user = User(**kwargs) user = User(**kwargs)
user.set_password(kwargs.get('password'))
user.save() user.save()
if groups_post: if groups_post:
group_select = [] group_select = []

View File

@ -9,7 +9,7 @@ import uuid as uuid_r
from django.db.models import Q from django.db.models import Q
from django.template import RequestContext from django.template import RequestContext
from django.db.models import ObjectDoesNotExist from django.db.models import ObjectDoesNotExist
from jumpserver.settings import MAIL_FROM, MAIL_ENABLE
from juser.user_api import * from juser.user_api import *
@ -240,8 +240,8 @@ def user_add(request):
if '' in [username, password, ssh_key_pwd, name, role]: if '' in [username, password, ssh_key_pwd, name, role]:
error = u'带*内容不能为空' error = u'带*内容不能为空'
raise ServerError raise ServerError
user_test = get_object(User, username=username) check_user_is_exist = User.objects.filter(username=username)
if user_test: if check_user_is_exist:
error = u'用户 %s 已存在' % username error = u'用户 %s 已存在' % username
raise ServerError raise ServerError
@ -250,10 +250,10 @@ def user_add(request):
else: else:
try: try:
user = db_add_user(username=username, name=name, user = db_add_user(username=username, name=name,
password=CRYPTOR.md5_crypt(password), password=password,
email=email, role=role, uuid=uuid, email=email, role=role, uuid=uuid,
groups=groups, admin_groups=admin_groups, groups=groups, admin_groups=admin_groups,
ssh_key_pwd=CRYPTOR.md5_crypt(ssh_key_pwd), ssh_key_pwd=ssh_key_pwd,
is_active=is_active, is_active=is_active,
date_joined=datetime.datetime.now()) date_joined=datetime.datetime.now())
server_add_user(username, password, ssh_key_pwd, ssh_key_login_need) server_add_user(username, password, ssh_key_pwd, ssh_key_login_need)
@ -417,8 +417,14 @@ def user_detail(request):
@require_role(role='admin') @require_role(role='admin')
def user_del(request): def user_del(request):
user_ids = request.GET.get('id', '') if request.method == "GET":
user_id_list = user_ids.split(',') user_ids = request.GET.get('id', '')
user_id_list = user_ids.split(',')
elif request.method == "POST":
user_ids = request.POST.get('id', '')
user_id_list = user_ids.split(',')
else:
return HttpResponse('错误请求')
for user_id in user_id_list: for user_id in user_id_list:
User.objects.filter(id=user_id).delete() User.objects.filter(id=user_id).delete()

0
manage.py Normal file → Executable file
View File