From fc22677f3fbe91e2688290c09010fa7bfdd3fbf3 Mon Sep 17 00:00:00 2001 From: ibuler Date: Tue, 9 Jun 2015 23:06:32 +0800 Subject: [PATCH] modify some --- connect.py | 131 +++++++++++++----------- jasset/models.py | 2 +- jlog/views.py | 5 +- jumpserver.conf | 1 + jumpserver/api.py | 249 ++++++++++++++++++++++++++++++++++++---------- 5 files changed, 278 insertions(+), 110 deletions(-) diff --git a/connect.py b/connect.py index 8bd93daac..d25d207d0 100644 --- a/connect.py +++ b/connect.py @@ -27,8 +27,8 @@ if django.get_version() != '1.6': django.setup() from juser.models import User from jlog.models import Log -from jumpserver.api import CONF, BASE_DIR, ServerError, user_perm_group_api, user_perm_group_hosts_api, get_user_host -from jumpserver.api import AssetAlias, get_connect_item +from jumpserver.api import CONF, BASE_DIR, ServerError, Juser +from jumpserver.api import AssetAlias, get_connect_item, logger try: import termios @@ -41,6 +41,7 @@ except ImportError: CONF.read(os.path.join(BASE_DIR, 'jumpserver.conf')) log_dir = os.path.join(BASE_DIR, 'logs') login_name = getpass.getuser() +user = Juser(username=login_name) def color_print(msg, color='blue'): @@ -177,52 +178,80 @@ def posix_shell(chan, username, host): log.log_finished = False log.end_time = datetime.datetime.now() log.save() - # print_prompt() -def get_user_host_group(username): - """ - Get the host groups of under the user control. - 获取用户有权限的主机组 - """ - groups_attr = {} - group_all = user_perm_group_api(username) - for group in group_all: - groups_attr[group.name] = [group.id, group.comment] - return groups_attr +# def get_user_host_group(username): +# """ +# Get the host groups of under the user control. +# 获取用户有权限的主机组 +# """ +# groups_attr = {} +# group_all = get_host_groups(username) +# for group in group_all: +# groups_attr[group.name] = [group.id, group.comment] +# return groups_attr -def get_host_group_host(username, gid): - """ - Get the host group hosts of under the user control. - 获取用户有权限主机组下的主机 - """ - groups_attr = get_user_host_group(username) - groups_ids = [attr[0] for name, attr in groups_attr.items()] - hosts_attr = {} - if gid in groups_ids: - user = User.objects.filter(username=username) - if user: - user = user[0] - hosts = user_perm_group_hosts_api(gid) - for host in hosts: - alias = AssetAlias.objects.filter(user=user, host=host) - if alias and alias[0].alias != '': - hosts_attr[host.ip] = [host.id, host.ip, alias[0].alias] - else: - hosts_attr[host.ip] = [host.id, host.ip, host.comment] - return hosts_attr +# def get_user_host_group_member(username, gid): +# """ +# Get the host group hosts of under the user control. +# 获取用户有权限主机组下的主机 +# """ +# groups_attr = get_user_host_group(username) +# groups_ids = [attr[0] for name, attr in groups_attr.items()] +# hosts_attr = {} +# if int(gid) in groups_ids: +# user = User.objects.filter(username=username) +# if user: +# user = user[0] +# hosts = get_host_groups(gid) +# for host in hosts: +# alias = AssetAlias.objects.filter(user=user, host=host) +# if alias and alias[0].alias != '': +# hosts_attr[host.ip] = [host.id, host.ip, alias[0].alias] +# else: +# hosts_attr[host.ip] = [host.id, host.ip, host.comment] +# return hosts_attr + + +# def user_asset_info(user, printable=False): +# """ +# Get or Print asset info +# 获取或打印用户资产信息 +# """ +# assets_info = {} +# try: +# assets = get_asset(user) +# except ServerError, e: +# color_print(e, 'red') +# return +# +# for asset in assets: +# asset_alias = AssetAlias.objects.filter(user=user, asset=asset) +# if asset_alias and asset_alias[0].alias != '': +# assets_info[asset.ip] = [asset.id, asset.ip, asset_alias[0].alias] +# else: +# assets_info[asset.ip] = [asset.id, asset.ip, asset.comment] +# +# if printable: +# ips = assets_info.keys() +# ips.sort() +# for ip in ips: +# print '%-15s -- %s' % (ip, assets_info[ip][2]) +# print '' +# else: +# return assets_info def verify_connect(username, part_ip): ip_matched = [] try: - hosts_attr = get_user_host(username) - hosts = hosts_attr.values() + assets = get_asset(username=username) except ServerError, e: color_print(e, 'red') return False + assets_info = for ip_info in hosts: if part_ip in ip_info[1:] and part_ip: ip_matched = [ip_info[1]] @@ -254,29 +283,16 @@ def print_prompt(): print textwrap.dedent(msg) -def print_user_host(username): - try: - hosts_attr = get_user_host(username) - except ServerError, e: - color_print(e, 'red') - return - hosts = hosts_attr.keys() - hosts.sort() - for ip in hosts: - print '%-15s -- %s' % (ip, hosts_attr[ip][2]) - print '' +# def print_user_host_group(username): +# host_groups = get_host_groups(username) +# for host_group in host_groups: +# print "[%3s] %s -- %s" % (host_group.id, host_group.ip, host_group.comment) -def print_user_hostgroup(username): - group_attr = get_user_host_group(username) - groups = group_attr.keys() - for g in groups: - print "[%3s] %s -- %s" % (group_attr[g][0], g, group_attr[g][1]) - - -def print_user_hostgroup_host(username, gid): +def asset_group_member(username, gid): pattern = re.compile(r'\d+') match = pattern.match(gid) + if match: hosts_attr = get_host_group_host(username, gid) hosts = hosts_attr.keys() @@ -397,6 +413,9 @@ def exec_cmd_servers(username): if __name__ == '__main__': + if not user.validate(): + color_print_exit(u'没有该用户 No that user.') + print_prompt() gid_pattern = re.compile(r'^g\d+$') try: @@ -409,10 +428,10 @@ if __name__ == '__main__': except KeyboardInterrupt: sys.exit(0) if option in ['P', 'p']: - print_user_host(login_name) + user.get_asset_info(printable=True) continue elif option in ['G', 'g']: - print_user_hostgroup(login_name) + user.get_asset_group_info(printable=True) continue elif gid_pattern.match(option): gid = option[1:].strip() diff --git a/jasset/models.py b/jasset/models.py index 416c4ddfa..cc3e0399b 100644 --- a/jasset/models.py +++ b/jasset/models.py @@ -47,7 +47,7 @@ class Asset(models.Model): class AssetAlias(models.Model): user = models.ForeignKey(User) - host = models.ForeignKey(Asset) + asset = models.ForeignKey(Asset) alias = models.CharField(max_length=100, blank=True, null=True) def __unicode__(self): diff --git a/jlog/views.py b/jlog/views.py index 29fc3e38d..0eb74f815 100644 --- a/jlog/views.py +++ b/jlog/views.py @@ -76,7 +76,10 @@ def log_kill(request): deptname = get_session_user_info(request)[4] if is_group_admin(request) and dept_name != deptname: return httperror(request, u'Kill失败, 您无权操作!') - os.kill(int(pid), 9) + try: + os.kill(int(pid), 9) + except OSError: + pass Log.objects.filter(pid=pid).update(is_finished=1, end_time=datetime.datetime.now()) return render_to_response('jlog/log_offline.html', locals(), context_instance=RequestContext(request)) else: diff --git a/jumpserver.conf b/jumpserver.conf index c4d294679..306da1e77 100644 --- a/jumpserver.conf +++ b/jumpserver.conf @@ -4,6 +4,7 @@ ip = 192.168.20.209 port = 80 key = 88aaaf7ffe3c6c04 +log = debug [db] diff --git a/jumpserver/api.py b/jumpserver/api.py index fa98cc350..3f23ff69a 100644 --- a/jumpserver/api.py +++ b/jumpserver/api.py @@ -23,20 +23,32 @@ from jasset.models import AssetAlias from django.core.exceptions import ObjectDoesNotExist from django.core.mail import send_mail import json +import logging 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') +# 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') SEND_IP = CONF.get('base', 'ip') SEND_PORT = CONF.get('base', 'port') MAIL_FROM = CONF.get('mail', 'email_host_user') +log_level = CONF.get('base', 'log') +log_level_total = {'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARN, 'error': logging.ERROR, + 'critical': logging.CRITICAL} +logger = logging.getLogger('jumpserver') +logger.setLevel(logging.DEBUG) +fh = logging.FileHandler(JLOG_FILE) +fh.setLevel(log_level_total.get(log_level, logging.DEBUG)) +formatter = logging.Formatter('%(asctime)s - %(filename)s - %(levelname)s - %(message)s') +fh.setFormatter(formatter) +logger.addHandler(fh) class LDAPMgmt(): @@ -87,14 +99,6 @@ class LDAPMgmt(): except ldap.LDAPError, e: print e - def decrypt(self, text): - cryptor = AES.new(self.key, self.mode, b'0000000000000000') - try: - plain_text = cryptor.decrypt(a2b_hex(text)) - except TypeError: - raise ServerError('Decrypt password error, TYpe error.') - return plain_text.rstrip('\0') - if LDAP_ENABLE: LDAP_HOST_URL = CONF.get('ldap', 'host_url') @@ -292,40 +296,199 @@ def user_group_perm_asset_group_api(user_group): return asset_group_list -def user_perm_group_api(username): - if username: - user = User.objects.get(username=username) +class Juser(object): + def __init__(self, username=None, uid=None): + if username: + user = User.objects.filter(username=username) + elif uid: + user = User.objects.filter(id=uid) + else: + user = '' + + if user: + user = user[0] + self.user = user + self.id = user.id + self.username = user.username + self.name = user.name + self.group = user.group.all() + + def validate(self): + """ + Validate is or not a true user + 鉴定用户 + """ + if self.user: + return True + else: + return False + + def get_asset_group(self): + """ + Get user host_groups. + 获取用户有权限的主机组 + """ + host_group_list = [] perm_list = [] - user_group_all = user.group.all() + user_group_all = self.user.group.all() for user_group in user_group_all: perm_list.extend(user_group.perm_set.all()) - asset_group_list = [] for perm in perm_list: - asset_group_list.append(perm.asset_group) - return asset_group_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]) + else: + return asset_groups_info + + def get_asset(self): + """ + Get the hosts of under the user control. + 获取主机列表 + """ + hosts = [] + host_groups = self.get_asset_group() + + for host_group in host_groups: + hosts.extend(get_asset_group_member(host_group.id)) + + return hosts + + def get_asset_info(self, printable=False): + """ + Get or print the user asset info + 获取或打印用户资产信息 + """ + assets_info = {} + assets = self.get_asset() + + for asset in assets: + asset_alias = AssetAlias.objects.filter(user=self.user, asset=asset) + if asset_alias and asset_alias[0].alias != '': + assets_info[asset.ip] = [asset.id, asset.ip, asset_alias[0].alias] + else: + assets_info[asset.ip] = [asset.id, asset.ip, 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 user_perm_group_hosts_api(gid): - hostgroup = BisGroup.objects.filter(id=gid) - if hostgroup: - return hostgroup[0].asset_set.all() - else: - return [] +class Jasset(object): + def __init__(self, ip=None, id=None): + if ip: + asset = Asset.objects.filter(ip=ip) + elif id: + asset = Asset.objects.filter(id=id) + else: + asset = '' + + if asset: + asset = asset[0] + self.asset = asset + self.ip = asset.ip + self.id = asset.id + self.port = asset.port + self.comment = asset.comment + + def validate(self): + if self.asset: + return True + else: + return False -def user_perm_asset_api(username): - user = User.objects.filter(username=username) - if user: - user = user[0] - asset_list = [] - asset_group_list = user_perm_group_api(user) - for asset_group in asset_group_list: - asset_list.extend(asset_group.asset_set.all()) - asset_list = list(set(asset_list)) - return asset_list - else: - return [] +class JassetGroup(object): + pass + + + +# def get_asset_group(user=None): +# """ +# Get user host_groups. +# 获取用户有权限的主机组 +# """ +# host_group_list = [] +# if user: +# user = user[0] +# perm_list = [] +# user_group_all = user.group.all() +# for user_group in user_group_all: +# perm_list.extend(user_group.perm_set.all()) +# +# host_group_list = [] +# for perm in perm_list: +# host_group_list.append(perm.asset_group) +# return host_group_list + + +def get_asset_group_member(gid): + """ + Get host_group's member host + 获取主机组下的主机 + """ + hosts = [] + if gid: + host_group = BisGroup.objects.filter(id=gid) + if host_group: + host_group = host_group[0] + hosts = host_group.asset_set.all() + return hosts + + +# def get_asset(user=None): +# """ +# Get the hosts of under the user control. +# 获取主机列表 +# """ +# hosts = [] +# if user: +# host_groups = get_asset_group(user) +# for host_group in host_groups: +# hosts.extend(get_asset_group_member(host_group.id)) +# return hosts + + +# def user_perm_asset_api(username): +# user = User.objects.filter(username=username) +# if user: +# user = user[0] +# asset_list = [] +# asset_group_list = user_perm_group_api(user) +# for asset_group in asset_group_list: +# asset_list.extend(asset_group.asset_set.all()) +# asset_list = list(set(asset_list)) +# return asset_list +# else: +# return [] def asset_perm_api(asset): @@ -346,24 +509,6 @@ def asset_perm_api(asset): return user_permed_list -def get_user_host(username): - """Get the hosts of under the user control.""" - hosts_attr = {} - asset_all = user_perm_asset_api(username) - user = User.objects.filter(username=username) - if user: - user = user[0] - for asset in asset_all: - alias = AssetAlias.objects.filter(user=user, host=asset) - if alias and alias[0].alias != '': - hosts_attr[asset.ip] = [asset.id, asset.ip, alias[0].alias] - else: - hosts_attr[asset.ip] = [asset.id, asset.ip, asset.comment] - return hosts_attr - else: - raise ServerError('User %s does not exit!' % username) - - def get_connect_item(username, ip): asset = get_object(Asset, ip=ip) port = int(asset.port)