跳板机管理平台
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.
 
 
 

812 lines
25 KiB

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import argparse
import sys
import os
import time
import logging
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, g
from flask_cors import CORS
# 启动flask
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)
# 命令行参数
gCmdArgs = {}
# 数据库文件
gSqlite3File = "/usr/local/jumpserver/jumpserver.db"
# 默认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"
# 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 init():
global gSqlite3File
jumpDb = os.environ.get("JUMPDB")
if jumpDb is not None:
gSqlite3File = jumpDb
else:
print("ERROR: Hadn't set environ var 'JUMPDB' for jump database! mod 755. Deault use %s" % gSqlite3File)
# exit(1)
# 解析命令行
def parse_cmd():
global gCmdArgs
# 显示默认值
default_value_fmt = " (default: %(default)s)"
# 参数
parser = argparse.ArgumentParser()
parser.add_argument("-host", type=str, help="bind host"+default_value_fmt, default="0.0.0.0")
parser.add_argument("-port", type=int, help="bind port"+default_value_fmt, default=8080)
parser.add_argument("-debug", type=bool, help="enable debug"+default_value_fmt, default=False)
# 解析
gCmdArgs = parser.parse_args()
logging.debug(gCmdArgs)
# 简单校验
if len(gCmdArgs.host) == 0 or gCmdArgs.port <= 0:
parser.print_help()
sys.exit(1)
# 主页url
global gUrl
gUrl = "http://%s:%d/" % (gCmdArgs.host, gCmdArgs.port)
# 只有执行结果
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:
logging.error("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:
# logging.error(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
# 处理请求前回调
@app.before_request
def before_request():
g.isconnect_db = False
if request.path != "/sso" and (not checkCookie(request)):
return redirect_sso()
# 连接db并标志
g.db = connect_db()
g.isconnect_db = True
# 处理请求后回调
@app.after_request
def after_request(response):
if g.isconnect_db:
g.db.close()
# g会被释放掉
return response
# sso回调接口
@app.route('/sso', methods=['GET', 'POST'])
def sso():
return do_sso(request)
# 处理sso回调
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():
return do_login(request)
# 主页
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template("index.html")
# 控制
@app.route('/jump/hosts', methods=['GET', 'POST'])
def hostlist():
return do_hostlist(request)
@app.route('/jump/users', methods=['GET', 'POST'])
def userlist():
return do_userlist(request)
# user动态路由
@app.route('/jump/user/<op>', methods=['GET', 'POST'])
def user_op(op):
if op == "add":
return do_add_user(request)
elif op == "del":
return do_del_user(request)
elif op == "modify":
return do_modify_user(request)
elif op == "hosts":
return do_userhostlist(request)
# host动态路由
@app.route('/jump/host/<op>', methods=['GET', 'POST'])
def host_op(op):
if op == "add":
return do_add_host(request)
elif op == "del":
return do_del_host(request)
elif op == "adduser":
return do_host_adduser(request)
elif op == "deluser":
return do_host_deluser(request)
elif op == "modifyuser":
return do_host_modifyuser(request)
elif op == "users":
return do_hostuserlist(request)
@app.route('/jump/hostuser', methods=['GET', 'POST'])
def hostuser():
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"
logging.info("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):
hosts = g.db.execute("select id,name,ip,port,desc,date from hosts where isdelete=0;").fetchall()
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):
users = g.db.execute("select id,name,sudo,desc,date from users where isdelete=0;").fetchall()
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"]
ret = g.db.execute("select count(1) from users where name='%s'" % name).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:
logging.error("output=%s", output)
return "error %s" % output
# 新增用户 sql
g.db.execute("insert into users(name,desc) values('%s',\"%s\")" %
(name, desc))
g.db.commit()
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:
logging.error("output=%s", output)
return "error %s" % output
g.db.execute("delete from users where name='%s'" % username)
g.db.execute("delete from hostuser where username='%s'" % username)
g.db.commit()
return "del user %s ok" % username
# 修改用户
def do_modify_user(request):
if request.method == "GET":
username = request.args.get('username')
password = request.args.get('password') or ""
sudo = int(request.args.get('sudo'))
desc = request.args.get('desc')
elif request.method == "POST":
username = request.form.get("username")
password = request.form.get("password") or ""
sudo = int(request.form.get("sudo"))
desc = request.form.get("desc")
else:
return "invalid request for user"
# check param
if sudo != 0 and sudo != 1:
return "invalid request sudo:%d param" % sudo
# 检查
users = g.db.execute("select sudo,desc from users where name='%s'" % username).fetchall()
if len(users) == 0:
logging.error("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:
logging.error("%s user user(%s) failed! => output=%s", opParam, username, output)
return "error: %s user user(%s) failed! => output=%s" % (opParam, username, output)
if len(password) > 0:
# 修改用户密码
opParam = "passwd"
status, output = exec_command_output(
"sudo sh manager_user.sh %s %s" % (opParam, username))
if status != 0:
logging.error("%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:
logging.debug("update users set sudo=%d,desc=\"%s\" where name='%s'", sudo, desc, username)
g.db.execute("update users set sudo=%d,desc=\"%s\" where name='%s'" % (sudo, desc, username))
g.db.commit()
logging.info("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"]
ret = g.db.execute(
"select count(1) from hosts where name='%s' or ip='%s'" % (name, ip)).fetchone()
if (len(ret) > 0 and ret[0]) >= 1:
return "alias name(%s) or ip(%s) is exists" % (name, ip)
# 新增用户 sql
g.db.execute("insert into hosts(name,ip,port,desc) values('%s','%s',%d,'%s')" % (
name, ip, port, desc))
g.db.execute("insert into hostuser(hostname,username,sudo) values('%s','%s','%d')" % (
name, gDefaultSSHAdmin, 1))
g.db.commit()
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"
g.db.execute("delete from hosts where name='%s' and ip='%s'" %
(hostname, ip))
g.db.execute("delete from hostuser where hostname='%s'" % hostname)
g.db.commit()
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"
# 检查
ret = g.db.execute("select count(1) from hostuser where hostname='%s' and username='%s'" % (
hostname, username)).fetchone()
if (len(ret) > 0 and ret[0]) >= 1:
logging.error("user(%s) exitst on host(%s)", username, hostname)
return "user(%s) exitst on host(%s)" % (username, hostname)
# 检查
hostips = g.db.execute("select ip,port from hosts where name='%s'" % (hostname)).fetchone()
if hostips == None:
logging.error("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:
logging.error("cat user(%s) id_rsa.pub failed!", username)
return "error %s" % publicSshRsaKey
logging.debug("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:
logging.error("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)
# 记录在数据库中
g.db.execute("insert into hostuser(hostname,username) values('%s','%s')" % (
hostname, username)).fetchone()
g.db.commit()
logging.info("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"
# 检查
ret = g.db.execute("select count(1) from hostuser where hostname='%s' and username='%s'" % (
hostname, username)).fetchone()
if (len(ret) > 0 and ret[0]) == 0:
logging.error("user(%s) not exitst on host(%s)", username, hostname)
return "user(%s) not exitst on host(%s)" % (username, hostname)
# 检查
hostips = g.db.execute("select ip,port from hosts where name='%s'" % (hostname)).fetchone()
if hostips == None:
logging.error("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:
logging.error("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)
# 记录在数据库中
g.db.execute("delete from hostuser where hostname='%s' and username='%s'" % (
hostname, username))
g.db.commit()
logging.info("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')
password = request.args.get('password') or ""
sudo = int(request.args.get('sudo'))
desc = request.args.get('desc')
elif request.method == "POST":
hostname = request.form.get("hostname")
username = request.form["username"]
password = request.form.get("password") or ""
sudo = int(request.form.get("username"))
desc = request.form.get("desc")
else:
return "invalid request for add user to host"
# 检查
hostusers = g.db.execute("select sudo,desc from hostuser where hostname='%s' and username='%s' and isdelete=0" % (
hostname, username)).fetchone()
if len(hostusers) > 0 and hostusers[0] != None:
logging.error("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"
# 检查
hostips = g.db.execute("select ip,port from hosts where name='%s'" % (hostname)).fetchone()
if hostips == None:
logging.error("host(%s) not exitst on hosts", hostname)
return "host(%s) not exitst on hosts" % hostname
hostip = hostips[0]
hostport = int(hostips[1])
if sudo != user_sudo:
change = True
# 主机上修改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:
logging.error("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 len(password) > 0:
# 主机上修改密码
opParam = "passwd"
status, output = exec_command_output(
"ssh %s@%s -p%d sudo sh .manager_user.sh %s %s %s" % (
gDefaultSSHAdmin, hostip, hostport, opParam, username, password))
if status != 0:
logging.error("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:
# 记录在数据库中
g.db.execute("update hostuser set sudo=%d,desc=%s where hostname='%s' and username='%s'" % (
sudo, desc, hostname, username))
g.db.commit()
logging.info("host remote =>> modify user:%s from host:%s successful [output: %s]", username, hostname, output)
return "host remote =>> modify user:%s from host:%s successful [output: %s]" % (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"
hosts = g.db.execute(
"select id,name,ip,port,desc,date from hosts where isdelete=0 and name in (select hostname from hostuser where username='%s')" % username).fetchall()
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"
users = g.db.execute(
"select id,username,sudo,date from hostuser where isdelete=0 and hostname='%s'" % hostname).fetchall()
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):
users = g.db.execute(
"select id,hostname,username,sudo,date from hostuser where isdelete=0").fetchall()
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 connect_db():
return sqlite3.connect(gSqlite3File)
# 初始化表
def init_db():
# 连接数据库
conn = connect_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 init_log():
# 设置日志
LOG_FORMAT = "[%(asctime)s %(levelname)s %(filename)s:%(funcName)s:%(lineno)d] => %(message)s"
logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT)
def main():
# 初始化检测
init()
# 初始化日志
init_log()
# 解析命令行
parse_cmd()
# 初始化db
init_db()
# 启动sso定时器 秒
Timer(SSO_TIMER_PERIOD, sso_timeout).start()
# 启动HTTP服务
app.run(
host=gCmdArgs.host,
port=gCmdArgs.port,
debug=gCmdArgs.debug
)
# 入口
if __name__ == '__main__':
main()