pull/6/head
halcyon 10 years ago
parent ef63fce7c4
commit bb94cfc7a1

@ -3,6 +3,7 @@
import socket
import sys
import os
import re
import ast
import select
import time
@ -23,7 +24,7 @@ from django.core.exceptions import ObjectDoesNotExist
os.environ['DJANGO_SETTINGS_MODULE'] = 'jumpserver.settings'
django.setup()
from juser.models import User
from jasset.models import Asset
from jasset.models import AssetAlias
from jlog.models import Log
from jumpserver.api import *
try:
@ -98,7 +99,7 @@ def log_record(username, host):
today_connect_log_dir = os.path.join(connect_log_dir, today)
log_filename = '%s_%s_%s.log' % (username, host, time_now)
log_file_path = os.path.join(today_connect_log_dir, log_filename)
dept_name = User.objects.get(username=username).dept
dept_name = User.objects.get(username=username).dept.name
pid = os.getpid()
ip_list = []
remote_ip = os.popen("who |grep `ps aux |gawk '{if ($2==%s) print $1}'` |gawk '{print $5}'|tr -d '()'" % pid).readlines()
@ -160,7 +161,6 @@ def posix_shell(chan, username, host):
chan.send(x)
finally:
timestamp_end = time.time()
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
log_file.write('Endtime is %s' % datetime.now())
log_file.close()
@ -168,14 +168,20 @@ def posix_shell(chan, username, host):
log.log_finished = False
log.end_time = datetime.now()
log.save()
print_prompt()
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.get(username=username)
for asset in asset_all:
hosts_attr[asset.ip] = [asset.id, asset.comment]
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
@ -188,6 +194,20 @@ def get_user_hostgroup(username):
return groups_attr
def get_user_hostgroup_host(username, gid):
"""Get the hostgroup hosts of under the user control."""
hosts_attr = {}
user = User.objects.get(username=username)
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_connect_item(username, ip):
asset = get_object(Asset, ip=ip)
@ -219,13 +239,16 @@ def get_connect_item(username, ip):
def verify_connect(username, part_ip):
ip_matched = []
hosts_attr = get_user_host(username)
hosts = hosts_attr.keys()
ip_matched = [ip for ip in hosts if part_ip in ip]
hosts = hosts_attr.values()
for ip_info in hosts:
for info in ip_info[1:]:
if part_ip in info:
ip_matched.append(ip_info[1])
if len(ip_matched) > 1:
for ip in ip_matched:
print '%s -- %s' % (ip, hosts_attr[ip][1])
print '%s -- %s' % (ip, hosts_attr[ip][2])
elif len(ip_matched) < 1:
color_print('No Permission or No host.', 'red')
else:
@ -238,8 +261,9 @@ def print_prompt():
1) Type \033[32mIP ADDRESS\033[0m To Login.
2) Type \033[32mP/p\033[0m To Print The Servers You Available.
3) Type \033[32mG/g\033[0m To Print The Server Groups You Available.
4) Type \033[32mE/e\033[0m To Execute Command On Several Servers.
5) Type \033[32mQ/q\033[0m To Quit.
4) Type \033[32mG/g+gid\033[0m To Print The Server Group Hosts You Available.
5) Type \033[32mE/e\033[0m To Execute Command On Several Servers.
6) Type \033[32mQ/q\033[0m To Quit.
"""
print textwrap.dedent(msg)
@ -249,14 +273,27 @@ def print_user_host(username):
hosts = hosts_attr.keys()
hosts.sort()
for ip in hosts:
print '%s -- %s' % (ip, hosts_attr[ip][1])
print '%-15s -- %s' % (ip, hosts_attr[ip][2])
def print_user_hostgroup(username):
group_attr = get_user_hostgroup(username)
groups = group_attr.keys()
for g in groups:
print '%s -- %s' % (g, group_attr[g][1])
print "[%3s]%s -- %s" % (group_attr[g][0], g, group_attr[g][1])
def print_user_hostgroup_host(username, gid):
pattern = re.compile(r'\d+')
match = pattern.match(gid)
if match:
hosts_attr = get_user_hostgroup_host(username, gid)
hosts = hosts_attr.keys()
hosts.sort()
for ip in hosts:
print '%-15s -- %s' % (ip, hosts_attr[ip][2])
else:
color_print('No such group id, Please check it.', 'red')
def connect(username, password, host, port, login_name):
@ -377,9 +414,13 @@ if __name__ == '__main__':
elif option in ['G', 'g']:
print_user_hostgroup(LOGIN_NAME)
continue
elif option.startswith('g') or option.startswith('G'):
gid = option[1:].strip()
print_user_hostgroup_host(LOGIN_NAME, gid)
continue
elif option in ['E', 'e']:
exec_cmd_servers(LOGIN_NAME)
elif option in ['Q', 'q']:
elif option in ['Q', 'q', 'exit']:
sys.exit()
else:
try:

@ -257,8 +257,9 @@ def view_splitter(request, su=None, adm=None):
raise Http404
def user_perm_group_api(user):
if user:
def user_perm_group_api(username):
if username:
user = User.objects.get(username=username)
perm_list = []
user_group_all = user.group.all()
for user_group in user_group_all:
@ -270,6 +271,14 @@ def user_perm_group_api(user):
return asset_group_list
def user_perm_group_hosts_api(gid):
hostgroup = BisGroup.objects.filter(id=gid)
if hostgroup:
return hostgroup[0].asset_set.all()
else:
return []
def user_perm_asset_api(username):
user = User.objects.filter(username=username)
if user:

@ -1,11 +1,13 @@
from django.conf.urls import patterns, include, url
from api import view_splitter
from views import index, admin_index
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'jumpserver.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
(r'^$', 'jumpserver.views.index'),
(r'^$', view_splitter, {'su': index, 'adm': admin_index}),
(r'^api/user/$', 'jumpserver.api.api_user'),
(r'^skin_config/$', 'jumpserver.views.skin_config'),
(r'^install/$', 'jumpserver.views.install'),

@ -45,7 +45,7 @@ def get_data(data, items, option):
return dic
@require_login
@require_super_user
def index(request):
users = User.objects.all()
hosts = Asset.objects.all()
@ -104,6 +104,69 @@ def index(request):
return render_to_response('index.html', locals(), context_instance=RequestContext(request))
@require_admin
def admin_index(request):
user_id = request.session.get('user_id', '')
user = User.objects.get(id=user_id)
dept = user.dept
dept_name = user.dept.name
users = User.objects.filter(dept=dept)
hosts = Asset.objects.filter(dept=dept)
online = Log.objects.filter(dept_name=dept_name, is_finished=0)
online_host = online.values('host').distinct()
online_user = online.values('user').distinct()
active_users = users.filter(is_active=1)
active_hosts = hosts.filter(is_active=1)
# percent of dashboard
percent_user = format(active_users.count() / users.count(), '.0%')
percent_host = format(active_hosts.count() / hosts.count(), '.0%')
percent_online_user = format(online_user.count() / users.count(), '.0%')
percent_online_host = format(online_host.count() / hosts.count(), '.0%')
li_date, li_str = getDaysByNum(7)
today = datetime.datetime.now().day
from_week = datetime.datetime.now() - datetime.timedelta(days=7)
week_data = Log.objects.filter(dept_name=dept_name, start_time__range=[from_week, datetime.datetime.now()])
user_top_ten = week_data.values('user').annotate(times=Count('user')).order_by('-times')[:10]
host_top_ten = week_data.values('host').annotate(times=Count('host')).order_by('-times')[:10]
user_dic, host_dic = get_data(week_data, user_top_ten, 'user'), get_data(week_data, host_top_ten, 'host')
# a week data
week_users = week_data.values('user').distinct().count()
week_hosts = week_data.count()
user_top_five = week_data.values('user').annotate(times=Count('user')).order_by('-times')[:5]
color = ['label-success', 'label-info', 'label-primary', 'label-default', 'label-warnning']
# perm apply latest 10
perm_apply_10 = Apply.objects.order_by('-date_add')[:10]
# latest 10 login
login_10 = Log.objects.order_by('-start_time')[:10]
# a week top 10
for user_info in user_top_ten:
username = user_info.get('user')
last = Log.objects.filter(user=username).latest('start_time')
user_info['last'] = last
print user_top_ten
top = {'user': '活跃用户数', 'host': '活跃主机数', 'times': '登录次数'}
top_dic = {}
for key, value in top.items():
li = []
for t in li_date:
year, month, day = t.year, t.month, t.day
if key != 'times':
times = week_data.filter(start_time__year=year, start_time__month=month, start_time__day=day).values(key).distinct().count()
else:
times = week_data.filter(start_time__year=year, start_time__month=month, start_time__day=day).count()
li.append(times)
top_dic[value] = li
return render_to_response('index.html', locals(), context_instance=RequestContext(request))
def skin_config(request):
return render_to_response('skin_config.html')
@ -184,28 +247,6 @@ def filter_ajax_api(request):
return render_to_response('filter_ajax_api.html', locals())
# def perm_user_asset(user_id=None, username=None):
# if user_id:
# user = User.objects.get(id=user_id)
# else:
# user = User.objects.get(username=username)
# user_groups = user.user_group.all()
# perms = []
# assets = []
# asset_groups = []
# for user_group in user_groups:
# perm = user_group.perm_set.all()
# perms.extend(perm)
#
# for perm in perms:
# asset_groups.extend(perm.asset_group.all())
#
# for asset_group in asset_groups:
# assets.extend(list(asset_group.asset_set.all()))
#
# return assets
def install(request):
from juser.models import DEPT, User
dept = DEPT(id=1, name="超管部", comment="超级管理员部门")

Loading…
Cancel
Save