You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
910 lines
26 KiB
910 lines
26 KiB
# -*- coding: UTF-8 -*-
|
|
|
|
import sys
|
|
import getopt
|
|
import os
|
|
import time
|
|
from threading import Timer
|
|
import subprocess
|
|
import sqlite3
|
|
import json
|
|
import urllib.parse as urlparse
|
|
from urllib.parse import urlencode
|
|
import hashlib
|
|
import requests
|
|
|
|
from flask import request, Flask, redirect, session, render_template
|
|
from flask_cors import CORS
|
|
|
|
app = Flask(__name__,
|
|
static_folder="/home/daniel/vue-admin/dist/static",
|
|
template_folder="/home/daniel/vue-admin/dist")
|
|
app.config['SECRET_KEY'] = os.urandom(24)
|
|
CORS(app)
|
|
|
|
# http bind
|
|
gHost = ""
|
|
gPort = 0
|
|
gDebug = 0
|
|
|
|
# 默认ssh管理账号
|
|
gDefaultSSHAdmin = "ec2-user"
|
|
|
|
# 默认初始密码
|
|
gDefaultInitPassword = "cynking"
|
|
|
|
# sql语句
|
|
gUsersTableSql = "create table if not exists users(id integer primary key autoincrement, name varchar(128) not null UNIQUE, sudo integer not null default 0, isdelete integer not null default 0, desc varchar(128), date timestamp not null default (datetime('now','localtime')))"
|
|
gHostsTableSql = "create table if not exists hosts(id integer primary key autoincrement, name varchar(128) not null UNIQUE, ip varchar(32) not null, port integer not null default 22, isdelete integer not null default 0, desc varchar(128), date timestamp not null default (datetime('now','localtime')))"
|
|
gHostUserSql = "create table if not exists hostuser(id integer primary key autoincrement, hostname varchar(128) not null, username varchar(128) not null, sudo integer not null default 0, isdelete integer not null default 0, date timestamp not null default (datetime('now','localtime')))"
|
|
|
|
# 添加跳板机用户脚本
|
|
gManagerUserShellFile = "manager_user.sh"
|
|
# 添加远程用户脚本
|
|
# gAddLocalUserShellFile = "add_remote_user.sh"
|
|
|
|
# sso应用信息
|
|
SSO_APPID = 18
|
|
SSO_APPTOKEN = "b813d5b7e4449177cd844bfb00ba8108"
|
|
SSO_URL = URL = "http://sso.cynking.cn/"
|
|
SSO_AUTH_URL = "http://sso.cynking.cn/?do=login.s_login&appid=%d" % SSO_APPID
|
|
|
|
# 服务主页地址
|
|
gUrl = "http://192.168.1.44:8080/"
|
|
# sso管理
|
|
gSsoManager = {}
|
|
# sso定时器执行周期
|
|
SSO_TIMER_PERIOD = 5*60
|
|
# sso过期时间
|
|
SSO_EXPIRE_TIMEOUT = 24*60*60
|
|
|
|
|
|
# 解析命令行
|
|
def parse_cmd():
|
|
''' 解析命令行参数 '''
|
|
global gHost, gPort, gDebug
|
|
try:
|
|
opts, _ = getopt.getopt(sys.argv[1:], "Hh:p:l:d:", [
|
|
"ip=", "port=", "debug="])
|
|
except getopt.GetoptError:
|
|
print('python3 %s -h <host> -p <port> -d <debug>' % (sys.argv[0]))
|
|
sys.exit(0)
|
|
for opt, arg in opts:
|
|
if opt == '-H':
|
|
print('python3 %s -h <host> -p <port> -d <debug>' % (sys.argv[0]))
|
|
sys.exit(0)
|
|
elif opt in ("-h", "--host"):
|
|
gHost = arg
|
|
elif opt in ("-p", "--port"):
|
|
gPort = int(arg)
|
|
elif opt in ("-l", "--debug"):
|
|
gDebug = int(arg)
|
|
|
|
if len(gHost) == 0 or gPort == 0:
|
|
print('python3 %s -h <host> -p <port> -d <debug>' % (sys.argv[0]))
|
|
sys.exit(0)
|
|
|
|
# 主页url
|
|
global gUrl
|
|
gUrl = "http://%s:%d/" % (gHost, gPort)
|
|
|
|
|
|
# 只有执行结果
|
|
def exec_command(cmd):
|
|
return subprocess.call(cmd, shell=True)
|
|
|
|
|
|
# 执行结果 和 输出
|
|
def exec_command_output(cmd):
|
|
return subprocess.getstatusoutput(cmd)
|
|
|
|
|
|
# 同步目标机sh文件
|
|
def sync_remote_control_file(host, port):
|
|
status, output = exec_command_output(
|
|
"scp -P %d manager_user.sh %s@%s:.manager_user.sh" % (port, gDefaultSSHAdmin, host))
|
|
if status != 0:
|
|
print("sync_remote_control_file error %s" % output)
|
|
return -1
|
|
return 0
|
|
|
|
|
|
# 重定向
|
|
def redirect_sso():
|
|
return '<script language="JavaScript">self.location="' + SSO_AUTH_URL + '";</script>'
|
|
|
|
|
|
# 计算md5
|
|
def make_md5(data):
|
|
md = hashlib.md5()
|
|
md.update(data.encode('utf-8'))
|
|
return md.hexdigest()
|
|
|
|
|
|
# 获取用户信息
|
|
def getUserInfo(params):
|
|
params["do"] = "user.getInfo"
|
|
params["appid"] = SSO_APPID
|
|
params["_time"] = int(time.time())
|
|
sort_params = sorted(params.items())
|
|
|
|
params = {}
|
|
for value in sort_params:
|
|
params[value[0]] = value[1]
|
|
|
|
params["sig"] = make_md5(urlencode(params) + SSO_APPTOKEN) # 签名
|
|
url = SSO_URL + "cmsapi.php"
|
|
|
|
resp = requests.get(url, params)
|
|
return json.loads(resp.text)
|
|
|
|
|
|
def checkCookie(request):
|
|
# 获取http参数
|
|
if request.method == "GET":
|
|
sso_uid = 0
|
|
_sso_uid = request.args.get('sso_uid')
|
|
if _sso_uid != None:
|
|
sso_uid = int(_sso_uid)
|
|
sso_token = request.args.get('sso_token')
|
|
elif request.method == "POST":
|
|
sso_uid = 0
|
|
_sso_uid = request.form.get("sso_uid")
|
|
if _sso_uid != None:
|
|
sso_uid = int(_sso_uid)
|
|
sso_token = request.form.get("sso_token")
|
|
|
|
# 获取sso信息有就保存
|
|
if sso_uid != None and sso_token != None and sso_uid != 0 and len(sso_token) > 0:
|
|
session["sso_uid"] = sso_uid
|
|
session["sso_token"] = sso_token
|
|
|
|
# 从session中获取sso信息
|
|
ck_uid = session.get("sso_uid")
|
|
ck_token = session.get("sso_token")
|
|
if ck_uid == None or ck_token == None or ck_uid == 0 or len(ck_token) == 0:
|
|
return False
|
|
|
|
# sso信息未过期则不需要验证
|
|
sso_info = gSsoManager.get(ck_uid)
|
|
if sso_info != None:
|
|
if sso_info["sso_token"] == ck_token:
|
|
return True
|
|
return False
|
|
|
|
# # 丢弃
|
|
# # 每次请求都验证用户信息太慢了
|
|
# params = {"sso_uid": ck_uid, "sso_token": ck_token}
|
|
# rets = getUserInfo(params)
|
|
|
|
# if rets == None:
|
|
# return False
|
|
# if rets["ret"] == -200:
|
|
# print(u"不信任的主机,请添加白名单")
|
|
# return False
|
|
# if rets["ret"] != 1:
|
|
# return False
|
|
# rets_data = rets.get("data")
|
|
# if rets_data == None:
|
|
# return False
|
|
# rets_data_uid = rets_data.get("uid")
|
|
# if rets_data_uid == None:
|
|
# return False
|
|
# return True
|
|
|
|
|
|
# sso回调接口
|
|
@app.route('/sso', methods=['GET', 'POST'])
|
|
def sso():
|
|
return do_sso(request)
|
|
|
|
|
|
def do_sso(request):
|
|
if request.method == "GET":
|
|
sso_uid = int(request.args.get('sso_uid'))
|
|
sso_token = request.args.get('sso_token')
|
|
elif request.method == "POST":
|
|
sso_uid = int(request.form.get("sso_uid"))
|
|
sso_token = request.form.get("sso_token")
|
|
|
|
# 记录sso信息
|
|
gSsoManager[sso_uid] = {
|
|
"sso_uid": sso_uid, "sso_token": sso_token, "update_time": int(time.time())}
|
|
|
|
params = urlparse.urlparse(request.url).query
|
|
return redirect(gUrl + "?" + params)
|
|
|
|
|
|
# 登录
|
|
@app.route('/login', methods=['GET', 'POST'])
|
|
def login():
|
|
if not checkCookie(request):
|
|
return redirect_sso()
|
|
return do_login(request)
|
|
|
|
|
|
# 主页
|
|
@app.route('/', methods=['GET', 'POST'])
|
|
def index():
|
|
if not checkCookie(request):
|
|
return redirect_sso()
|
|
return render_template("index.html")
|
|
|
|
|
|
# 控制
|
|
@app.route('/jump/hosts', methods=['GET', 'POST'])
|
|
def hostlist():
|
|
if not checkCookie(request):
|
|
return redirect_sso()
|
|
return do_hostlist(request)
|
|
|
|
|
|
@app.route('/jump/users', methods=['GET', 'POST'])
|
|
def userlist():
|
|
if not checkCookie(request):
|
|
return redirect_sso()
|
|
return do_userlist(request)
|
|
|
|
|
|
@app.route('/jump/user/add', methods=['GET', 'POST'])
|
|
def add_user():
|
|
if not checkCookie(request):
|
|
return redirect_sso()
|
|
return do_add_user(request)
|
|
|
|
|
|
@app.route('/jump/user/del', methods=['GET', 'POST'])
|
|
def del_user():
|
|
if not checkCookie(request):
|
|
return redirect_sso()
|
|
return do_del_user(request)
|
|
|
|
|
|
@app.route('/jump/user/sudo', methods=['GET', 'POST'])
|
|
def sudo_user():
|
|
if not checkCookie(request):
|
|
return redirect_sso()
|
|
return do_sudo_user(request)
|
|
|
|
|
|
@app.route('/jump/user/unsudo', methods=['GET', 'POST'])
|
|
def unsudo_user():
|
|
if not checkCookie(request):
|
|
return redirect_sso()
|
|
return do_unsudo_user(request)
|
|
|
|
|
|
@app.route('/jump/user/modify', methods=['GET', 'POST'])
|
|
def modify_user():
|
|
if not checkCookie(request):
|
|
return redirect_sso()
|
|
return do_modify_user(request)
|
|
|
|
|
|
@app.route('/jump/user/hosts', methods=['GET', 'POST'])
|
|
def userhostlist():
|
|
if not checkCookie(request):
|
|
return redirect_sso()
|
|
return do_userhostlist(request)
|
|
|
|
|
|
@app.route('/jump/host/add', methods=['GET', 'POST'])
|
|
def add_host():
|
|
if not checkCookie(request):
|
|
return redirect_sso()
|
|
return do_add_host(request)
|
|
|
|
|
|
@app.route('/jump/host/del', methods=['GET', 'POST'])
|
|
def del_host():
|
|
if not checkCookie(request):
|
|
return redirect_sso()
|
|
return do_del_host(request)
|
|
|
|
|
|
@app.route('/jump/host/adduser', methods=['GET', 'POST'])
|
|
def host_adduser():
|
|
if not checkCookie(request):
|
|
return redirect_sso()
|
|
return do_host_adduser(request)
|
|
|
|
|
|
@app.route('/jump/host/deluser', methods=['GET', 'POST'])
|
|
def host_deluser():
|
|
if not checkCookie(request):
|
|
return redirect_sso()
|
|
return do_host_deluser(request)
|
|
|
|
|
|
@app.route('/jump/host/sudouser', methods=['GET', 'POST'])
|
|
def host_sudouser():
|
|
if not checkCookie(request):
|
|
return redirect_sso()
|
|
return do_host_sudouser(request)
|
|
|
|
|
|
@app.route('/jump/host/unsudouser', methods=['GET', 'POST'])
|
|
def host_unsudouser():
|
|
if not checkCookie(request):
|
|
return redirect_sso()
|
|
return do_host_unsudouser(request)
|
|
|
|
|
|
@app.route('/jump/host/modifyuser', methods=['GET', 'POST'])
|
|
def host_modifyuser():
|
|
if not checkCookie(request):
|
|
return redirect_sso()
|
|
return do_host_modifyuser(request)
|
|
|
|
|
|
@app.route('/jump/host/users', methods=['GET', 'POST'])
|
|
def hostuserlist():
|
|
if not checkCookie(request):
|
|
return redirect_sso()
|
|
return do_hostuserlist(request)
|
|
|
|
|
|
@app.route('/jump/hostuser', methods=['GET', 'POST'])
|
|
def hostuser():
|
|
if not checkCookie(request):
|
|
return redirect_sso()
|
|
return do_hostuserall(request)
|
|
|
|
|
|
def do_login(request):
|
|
if request.method == "GET":
|
|
username = request.args.get('username')
|
|
password = request.args.get('password')
|
|
elif request.method == "POST":
|
|
username = request.form.get("username") or "admin"
|
|
password = request.form.get("password") or "123456"
|
|
|
|
print("login username:%s password:%s" % (username, password))
|
|
resp = {}
|
|
resp["msg"] = "ok"
|
|
resp["code"] = 200
|
|
resp["user"] = username
|
|
resp["sessionkey"] = "cookie-666"
|
|
return json.dumps(resp)
|
|
|
|
|
|
# get主机列表
|
|
def do_hostlist(request):
|
|
conn, cur = get_db()
|
|
cur.execute("select id,name,ip,port,desc,date from hosts where isdelete=0;")
|
|
hosts = cur.fetchall()
|
|
cur.close()
|
|
conn.close()
|
|
|
|
resp = []
|
|
for host in hosts:
|
|
res = {}
|
|
res["id"] = host[0]
|
|
res["name"] = host[1]
|
|
res["ip"] = host[2]
|
|
res["port"] = host[3]
|
|
res["desc"] = host[4]
|
|
res["ctime"] = host[5]
|
|
resp.append(res)
|
|
return json.dumps(resp)
|
|
|
|
|
|
# 获取用户列表
|
|
def do_userlist(request):
|
|
conn, cur = get_db()
|
|
cur.execute("select id,name,sudo,desc,date from users where isdelete=0;")
|
|
users = cur.fetchall()
|
|
cur.close()
|
|
conn.close()
|
|
|
|
resp = []
|
|
for user in users:
|
|
res = {}
|
|
res["id"] = user[0]
|
|
res["name"] = user[1]
|
|
res["sudo"] = user[2]
|
|
res["desc"] = user[3]
|
|
res["ctime"] = user[4]
|
|
resp.append(res)
|
|
return json.dumps(resp)
|
|
|
|
# 添加用户
|
|
def do_add_user(request):
|
|
if request.method == "GET":
|
|
name = request.args.get('name')
|
|
desc = request.args.get('desc')
|
|
elif request.method == "POST":
|
|
name = request.form["name"]
|
|
desc = request.form["desc"]
|
|
|
|
conn, cur = get_db()
|
|
cur.execute("select count(1) from users where name='%s'" % name)
|
|
ret = cur.fetchone()
|
|
if (len(ret) > 0 and ret[0]) >= 1:
|
|
return "user %s exists" % name
|
|
|
|
status, output = exec_command_output("sudo sh %s add %s \"%s\"" % (
|
|
gManagerUserShellFile, name, gDefaultInitPassword))
|
|
if status != 0:
|
|
print("output=%s" % output)
|
|
return "error %s" % output
|
|
|
|
# 新增用户 sql
|
|
cur.execute("insert into users(name,desc) values('%s',\"%s\")" %
|
|
(name, desc))
|
|
conn.commit()
|
|
cur.close()
|
|
conn.close()
|
|
return "ok"
|
|
|
|
|
|
# 删除用户
|
|
def do_del_user(request):
|
|
if request.method == "GET":
|
|
username = request.args.get('name')
|
|
elif request.method == "POST":
|
|
username = request.form["name"]
|
|
else:
|
|
return "invalid request for del user"
|
|
|
|
status, output = exec_command_output(
|
|
"sudo sh %s del %s" % (gManagerUserShellFile, username))
|
|
if status != 0:
|
|
print("output=%s" % output)
|
|
return "error %s" % output
|
|
|
|
conn, cur = get_db()
|
|
cur.execute("delete from users where name='%s'" % username)
|
|
cur.execute("delete from hostuser where username='%s'" % username)
|
|
conn.commit()
|
|
cur.close()
|
|
conn.close()
|
|
return "del user %s ok" % username
|
|
|
|
|
|
# 修改用户
|
|
def do_modify_user(request):
|
|
if request.method == "GET":
|
|
username = request.args.get('username')
|
|
sudo = int(request.args.get('sudo'))
|
|
desc = request.args.get('desc')
|
|
elif request.method == "POST":
|
|
username = request.form["username"]
|
|
sudo = int(request.form["sudo"])
|
|
desc = request.form["desc"]
|
|
else:
|
|
return "invalid request for user"
|
|
|
|
# check param
|
|
if sudo != 0 and sudo != 1:
|
|
return "invalid request sudo:%d param" % sudo
|
|
|
|
# 需求数据库
|
|
conn, cur = get_db()
|
|
|
|
# 检查
|
|
cur.execute("select sudo,desc from users where name='%s'" % username)
|
|
users = cur.fetchall()
|
|
if len(users) == 0:
|
|
print("user(%s) not exitst" % username)
|
|
return "user(%s) not exitst" % username
|
|
|
|
user = users[0]
|
|
user_sudo = user[0]
|
|
user_desc = user[1]
|
|
change = False # 是否需要修改
|
|
opParam = "sudo" # 操作类型 sudo / unsudo
|
|
if sudo == 0:
|
|
opParam = "unsudo"
|
|
|
|
if sudo != user_sudo:
|
|
change = True
|
|
|
|
# 处理sudo权限
|
|
status, output = exec_command_output(
|
|
"sudo sh manager_user.sh %s %s" % (opParam, username))
|
|
if status != 0:
|
|
print("%s user user(%s) failed! => output=%s" %
|
|
(opParam, username, output))
|
|
return "error: %s user user(%s) failed! => output=%s" % (opParam, username, output)
|
|
|
|
if desc != user_desc:
|
|
change = True
|
|
|
|
# 记录在数据库中
|
|
if change:
|
|
print("update users set sudo=%d,desc=\"%s\" where name='%s'" %
|
|
(sudo, desc, username))
|
|
cur.execute("update users set sudo=%d,desc=\"%s\" where name='%s'" % (
|
|
sudo, desc, username))
|
|
conn.commit()
|
|
|
|
# 清理数据库
|
|
cur.close()
|
|
conn.close()
|
|
print("modify user:%s successful [output: %s]" % (username, output))
|
|
return "modify user:%s successful [output: %s]" % (username, output)
|
|
|
|
|
|
# 添加主机
|
|
def do_add_host(request):
|
|
if request.method == "GET":
|
|
name = request.args.get('name')
|
|
ip = request.args.get('host')
|
|
port = int(request.args.get('port'))
|
|
desc = request.args.get('desc')
|
|
elif request.method == "POST":
|
|
name = request.form["name"]
|
|
ip = request.form["host"]
|
|
port = int(request.form["port"])
|
|
desc = request.form["desc"]
|
|
|
|
conn, cur = get_db()
|
|
cur.execute(
|
|
"select count(1) from hosts where name='%s' or ip='%s'" % (name, ip))
|
|
ret = cur.fetchone()
|
|
if (len(ret) > 0 and ret[0]) >= 1:
|
|
return "alias name(%s) or ip(%s) is exists" % (name, ip)
|
|
|
|
# 新增用户 sql
|
|
cur.execute("insert into hosts(name,ip,port,desc) values('%s','%s',%d,'%s')" % (
|
|
name, ip, port, desc))
|
|
cur.execute("insert into hostuser(hostname,username,sudo) values('%s','%s','%d')" % (
|
|
name, gDefaultSSHAdmin, 1))
|
|
conn.commit()
|
|
|
|
cur.close()
|
|
conn.close()
|
|
return "add host %s:%s ok" % (name, ip)
|
|
|
|
|
|
# 删除主机
|
|
def do_del_host(request):
|
|
if request.method == "GET":
|
|
hostname = request.args.get('name')
|
|
ip = request.args.get('host')
|
|
elif request.method == "POST":
|
|
hostname = request.form["name"]
|
|
ip = request.form["host"]
|
|
else:
|
|
return "invalid request for del host"
|
|
|
|
conn, cur = get_db()
|
|
cur.execute("delete from hosts where name='%s' and ip='%s'" %
|
|
(hostname, ip))
|
|
cur.execute("delete from hostuser where hostname='%s'" % hostname)
|
|
conn.commit()
|
|
|
|
cur.close()
|
|
conn.close()
|
|
return "delete host %s:%s ok" % (hostname, ip)
|
|
|
|
|
|
# 主机上添加用户
|
|
def do_host_adduser(request):
|
|
if request.method == "GET":
|
|
hostname = request.args.get('hostname')
|
|
username = request.args.get('username')
|
|
elif request.method == "POST":
|
|
hostname = request.form["hostname"]
|
|
username = request.form["username"]
|
|
else:
|
|
return "invalid request for add user to host"
|
|
|
|
# 需求数据库
|
|
conn, cur = get_db()
|
|
# 检查
|
|
cur.execute("select count(1) from hostuser where hostname='%s' and username='%s'" % (
|
|
hostname, username))
|
|
ret = cur.fetchone()
|
|
if (len(ret) > 0 and ret[0]) >= 1:
|
|
print("user(%s) exitst on host(%s)" % (username, hostname))
|
|
return "user(%s) exitst on host(%s)" % (username, hostname)
|
|
|
|
# 检查
|
|
cur.execute("select ip,port from hosts where name='%s'" % (hostname))
|
|
hostips = cur.fetchone()
|
|
if hostips == None:
|
|
print("host(%s) not exitst on hosts" % hostname)
|
|
return "host(%s) not exitst on hosts" % hostname
|
|
hostip = hostips[0]
|
|
hostport = int(hostips[1])
|
|
|
|
# 同步控制文件
|
|
sync_remote_control_file(hostip, hostport)
|
|
|
|
# 获取公钥
|
|
status, publicSshRsaKey = exec_command_output(
|
|
"sudo cat /home/%s/.ssh/id_rsa.pub" % username)
|
|
if status != 0:
|
|
print("cat user(%s) id_rsa.pub failed!", username)
|
|
return "error %s" % publicSshRsaKey
|
|
|
|
print("ssh %s@%s -p%d sudo sh .manager_user.sh add %s %s \"\"%s\"\"" %
|
|
(gDefaultSSHAdmin, hostip, hostport, username, gDefaultInitPassword, publicSshRsaKey))
|
|
# 主机上新建用户
|
|
status, output = exec_command_output("ssh %s@%s -p%d sudo sh .manager_user.sh add %s %s \"\"%s\"\"" % (
|
|
gDefaultSSHAdmin, hostip, hostport, username, gDefaultInitPassword, publicSshRsaKey))
|
|
if status != 0:
|
|
print("remote add user host(%s) user(%s) failed! => output=%s" %
|
|
(hostname, username, output))
|
|
return "error: remote add user host(%s) user(%s) failed! => output=%s" % (hostname, username, output)
|
|
|
|
# 记录在数据库中
|
|
cur.execute("insert into hostuser(hostname,username) values('%s','%s')" % (
|
|
hostname, username))
|
|
cur.fetchone()
|
|
conn.commit()
|
|
|
|
# 清理数据库
|
|
cur.close()
|
|
conn.close()
|
|
print("host remote =>> add user:%s to host:%s successful [output: %s]" % (
|
|
username, hostname, output))
|
|
return "host remote =>> add user:%s to host:%s successful" % (username, hostname)
|
|
|
|
|
|
# 主机上删除用户
|
|
def do_host_deluser(request):
|
|
if request.method == "GET":
|
|
hostname = request.args.get('hostname')
|
|
username = request.args.get('username')
|
|
elif request.method == "POST":
|
|
hostname = request.form["hostname"]
|
|
username = request.form["username"]
|
|
else:
|
|
return "invalid request for add user to host"
|
|
|
|
# 需求数据库
|
|
conn, cur = get_db()
|
|
|
|
# 检查
|
|
cur.execute("select count(1) from hostuser where hostname='%s' and username='%s'" % (
|
|
hostname, username))
|
|
ret = cur.fetchone()
|
|
if (len(ret) > 0 and ret[0]) == 0:
|
|
print("user(%s) not exitst on host(%s)" % (username, hostname))
|
|
return "user(%s) not exitst on host(%s)" % (username, hostname)
|
|
|
|
# 检查
|
|
cur.execute("select ip,port from hosts where name='%s'" % (hostname))
|
|
hostips = cur.fetchone()
|
|
if hostips == None:
|
|
print("host(%s) not exitst on hosts" % hostname)
|
|
return "host(%s) not exitst on hosts" % hostname
|
|
hostip = hostips[0]
|
|
hostport = int(hostips[1])
|
|
|
|
# 同步控制文件
|
|
sync_remote_control_file(hostip, hostport)
|
|
|
|
# 主机上新建用户
|
|
status, output = exec_command_output(
|
|
"ssh %s@%s -p%d sudo sh .manager_user.sh del %s" % (gDefaultSSHAdmin, hostip, hostport, username))
|
|
if status != 0:
|
|
print("remote del user host(%s) user(%s) failed! => output=%s" %
|
|
(hostname, username, output))
|
|
return "error: remote del user host(%s) user(%s) failed! => output=%s" % (hostname, username, output)
|
|
|
|
# 记录在数据库中
|
|
cur.execute("delete from hostuser where hostname='%s' and username='%s'" % (
|
|
hostname, username))
|
|
conn.commit()
|
|
|
|
# 清理数据库
|
|
cur.close()
|
|
conn.close()
|
|
print("host remote =>> del user:%s from host:%s successful [output: %s]" % (
|
|
username, hostname, output))
|
|
return "host remote =>> del user:%s from host:%s successful" % (username, hostname)
|
|
|
|
# 主机上修改用户信息
|
|
def do_host_modifyuser(request):
|
|
if request.method == "GET":
|
|
hostname = request.args.get('hostname')
|
|
username = request.args.get('username')
|
|
sudo = int(request.args.get('sudo'))
|
|
desc = request.args.get('desc')
|
|
elif request.method == "POST":
|
|
hostname = request.form["hostname"]
|
|
username = request.form["username"]
|
|
sudo = int(request.form["username"])
|
|
desc = request.form["desc"]
|
|
else:
|
|
return "invalid request for add user to host"
|
|
|
|
# 需求数据库
|
|
conn, cur = get_db()
|
|
|
|
# 检查
|
|
cur.execute("select sudo,desc from hostuser where hostname='%s' and username='%s' and isdelete=0" % (
|
|
hostname, username))
|
|
hostusers = cur.fetchone()
|
|
if len(hostusers) > 0 and hostusers[0] != None:
|
|
print("user(%s) not exitst on host(%s)" % (username, hostname))
|
|
return "user(%s) not exitst on host(%s)" % (username, hostname)
|
|
|
|
hostuser = hostusers[0]
|
|
|
|
user_sudo = hostuser[0]
|
|
user_desc = hostuser[1]
|
|
change = False
|
|
opParam = "sudo"
|
|
|
|
if sudo == 0:
|
|
opParam = "unsudo"
|
|
|
|
if sudo != user_sudo:
|
|
change = True
|
|
|
|
# 检查
|
|
cur.execute("select ip,port from hosts where name='%s'" % (hostname))
|
|
hostips = cur.fetchone()
|
|
if hostips == None:
|
|
print("host(%s) not exitst on hosts" % hostname)
|
|
return "host(%s) not exitst on hosts" % hostname
|
|
|
|
hostip = hostips[0]
|
|
hostport = int(hostips[1])
|
|
|
|
# 主机上修改sudo
|
|
status, output = exec_command_output(
|
|
"ssh %s@%s -p%d sudo sh .manager_user.sh %s %s" % (gDefaultSSHAdmin, hostip, hostport, opParam, username))
|
|
if status != 0:
|
|
print("remote %s user host(%s) user(%s) failed! => output=%s" %
|
|
(opParam, hostname, username, output))
|
|
return "error: remote %s user host(%s) user(%s) failed! => output=%s" % (opParam, hostname, username, output)
|
|
|
|
if desc != user_desc:
|
|
change = True
|
|
|
|
if change:
|
|
# 记录在数据库中
|
|
cur.execute("update hostuser set sudo=%d,desc=%s where hostname='%s' and username='%s'" % (
|
|
sudo, desc, hostname, username))
|
|
conn.commit()
|
|
|
|
# 清理数据库
|
|
cur.close()
|
|
conn.close()
|
|
print("host remote =>> %s user:%s from host:%s successful [output: %s]" % (
|
|
opParam, username, hostname, output))
|
|
return "host remote =>> %s user:%s from host:%s successful [output: %s]" % (opParam, username, hostname, output)
|
|
|
|
|
|
# 获取用户所有的主机列表
|
|
def do_userhostlist(request):
|
|
if request.method == "GET":
|
|
username = request.args.get('username')
|
|
elif request.method == "POST":
|
|
username = request.form["username"]
|
|
else:
|
|
return "invalid request for getting user host list"
|
|
|
|
conn, cur = get_db()
|
|
cur.execute("select id,name,ip,port,desc,date from hosts where isdelete=0 and name in (select hostname from hostuser where username='%s')" % username)
|
|
hosts = cur.fetchall()
|
|
cur.close()
|
|
conn.close()
|
|
|
|
resp = []
|
|
for host in hosts:
|
|
res = {}
|
|
res["id"] = host[0]
|
|
res["name"] = host[1]
|
|
res["ip"] = host[2]
|
|
res["port"] = host[3]
|
|
res["desc"] = host[4]
|
|
res["ctime"] = host[5]
|
|
resp.append(res)
|
|
return json.dumps(resp)
|
|
|
|
|
|
# 获取主机上的用户列表
|
|
def do_hostuserlist(request):
|
|
if request.method == "GET":
|
|
hostname = request.args.get('hostname')
|
|
elif request.method == "POST":
|
|
hostname = request.form["hostname"]
|
|
else:
|
|
return "invalid request for getting host user list"
|
|
|
|
conn, cur = get_db()
|
|
cur.execute(
|
|
"select id,username,sudo,date from hostuser where isdelete=0 and hostname='%s'" % hostname)
|
|
users = cur.fetchall()
|
|
cur.close()
|
|
conn.close()
|
|
|
|
resp = []
|
|
for user in users:
|
|
res = {}
|
|
res["id"] = user[0]
|
|
res["username"] = user[1]
|
|
res["sudo"] = user[2]
|
|
res["ctime"] = user[3]
|
|
resp.append(res)
|
|
return json.dumps(resp)
|
|
|
|
|
|
# 获取所有的用户主机列表
|
|
def do_hostuserall(request):
|
|
conn, cur = get_db()
|
|
cur.execute(
|
|
"select id,hostname,username,sudo,date from hostuser where isdelete=0")
|
|
users = cur.fetchall()
|
|
cur.close()
|
|
conn.close()
|
|
|
|
resp = []
|
|
for user in users:
|
|
res = {}
|
|
res["id"] = user[0]
|
|
res["hostname"] = user[1]
|
|
res["username"] = user[2]
|
|
res["sudo"] = user[3]
|
|
res["ctime"] = user[4]
|
|
resp.append(res)
|
|
return json.dumps(resp)
|
|
|
|
|
|
# 连接数据库
|
|
def get_db():
|
|
conn = sqlite3.connect('/usr/local/jumpserver/jumpserver.db')
|
|
curr = conn.cursor()
|
|
return conn, curr
|
|
|
|
|
|
# 初始化表
|
|
def init_db():
|
|
# 连接数据库
|
|
conn, _ = get_db()
|
|
if conn == None:
|
|
sys.exit(1)
|
|
|
|
# 初始化表
|
|
conn.execute(gUsersTableSql)
|
|
conn.execute(gHostsTableSql)
|
|
# 创建主机数据库
|
|
conn.execute(gHostUserSql)
|
|
|
|
|
|
# sso本地管理
|
|
def sso_timeout():
|
|
# 当前时间戳
|
|
nowtime = int(time.time())
|
|
# 需求删除的key
|
|
delkeys = []
|
|
for sso_uid, sso_info in gSsoManager.items():
|
|
if nowtime - sso_info["update_time"] >= SSO_EXPIRE_TIMEOUT:
|
|
delkeys.append(sso_uid)
|
|
|
|
# 删除key
|
|
for key in delkeys:
|
|
del gSsoManager[key]
|
|
|
|
# 循环定时器
|
|
Timer(SSO_TIMER_PERIOD, sso_timeout).start()
|
|
|
|
|
|
def main():
|
|
# 解析命令行
|
|
parse_cmd()
|
|
|
|
# 初始化db
|
|
init_db()
|
|
|
|
# 启动sso定时器 秒
|
|
Timer(SSO_TIMER_PERIOD, sso_timeout).start()
|
|
|
|
# 启动HTTP服务
|
|
app.run(
|
|
host=gHost,
|
|
port=gPort,
|
|
debug=gDebug
|
|
)
|
|
|
|
|
|
# 入口
|
|
if __name__ == '__main__':
|
|
main()
|