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

796 lines
24 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. # -*- coding: UTF-8 -*-
  2. import sys
  3. import getopt
  4. import os
  5. import time
  6. from threading import Timer
  7. import subprocess
  8. import sqlite3
  9. import json
  10. import urllib.parse as urlparse
  11. from urllib.parse import urlencode
  12. import hashlib
  13. import requests
  14. from flask import request, Flask, redirect, session, render_template, g
  15. from flask_cors import CORS
  16. app = Flask(__name__,
  17. static_folder="/home/daniel/vue-admin/dist/static",
  18. template_folder="/home/daniel/vue-admin/dist")
  19. app.config['SECRET_KEY'] = os.urandom(24)
  20. CORS(app)
  21. # http bind
  22. gHost = ""
  23. gPort = 0
  24. gDebug = 0
  25. # 数据库文件
  26. gSqlite3File = "/usr/local/jumpserver/jumpserver.db"
  27. # 默认ssh管理账号
  28. gDefaultSSHAdmin = "ec2-user"
  29. # 默认初始密码
  30. gDefaultInitPassword = "cynking"
  31. # sql语句
  32. 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')))"
  33. 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')))"
  34. 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')))"
  35. # 添加跳板机用户脚本
  36. gManagerUserShellFile = "manager_user.sh"
  37. # 添加远程用户脚本
  38. # gAddLocalUserShellFile = "add_remote_user.sh"
  39. # sso应用信息
  40. SSO_APPID = 18
  41. SSO_APPTOKEN = "b813d5b7e4449177cd844bfb00ba8108"
  42. SSO_URL = URL = "http://sso.cynking.cn/"
  43. SSO_AUTH_URL = "http://sso.cynking.cn/?do=login.s_login&appid=%d" % SSO_APPID
  44. # 服务主页地址
  45. gUrl = "http://192.168.1.44:8080/"
  46. # sso管理
  47. gSsoManager = {}
  48. # sso定时器执行周期
  49. SSO_TIMER_PERIOD = 5*60
  50. # sso过期时间
  51. SSO_EXPIRE_TIMEOUT = 24*60*60
  52. # 解析命令行
  53. def parse_cmd():
  54. ''' 解析命令行参数 '''
  55. global gHost, gPort, gDebug
  56. try:
  57. opts, _ = getopt.getopt(sys.argv[1:], "Hh:p:l:d:", [
  58. "ip=", "port=", "debug="])
  59. except getopt.GetoptError:
  60. print('python3 %s -h <host> -p <port> -d <debug>' % (sys.argv[0]))
  61. sys.exit(0)
  62. for opt, arg in opts:
  63. if opt == '-H':
  64. print('python3 %s -h <host> -p <port> -d <debug>' % (sys.argv[0]))
  65. sys.exit(0)
  66. elif opt in ("-h", "--host"):
  67. gHost = arg
  68. elif opt in ("-p", "--port"):
  69. gPort = int(arg)
  70. elif opt in ("-l", "--debug"):
  71. gDebug = int(arg)
  72. if len(gHost) == 0 or gPort == 0:
  73. print('python3 %s -h <host> -p <port> -d <debug>' % (sys.argv[0]))
  74. sys.exit(0)
  75. # 主页url
  76. global gUrl
  77. gUrl = "http://%s:%d/" % (gHost, gPort)
  78. # 只有执行结果
  79. def exec_command(cmd):
  80. return subprocess.call(cmd, shell=True)
  81. # 执行结果 和 输出
  82. def exec_command_output(cmd):
  83. return subprocess.getstatusoutput(cmd)
  84. # 同步目标机sh文件
  85. def sync_remote_control_file(host, port):
  86. status, output = exec_command_output(
  87. "scp -P %d manager_user.sh %s@%s:.manager_user.sh" % (port, gDefaultSSHAdmin, host))
  88. if status != 0:
  89. print("sync_remote_control_file error %s" % output)
  90. return -1
  91. return 0
  92. # 重定向
  93. def redirect_sso():
  94. return '<script language="JavaScript">self.location="' + SSO_AUTH_URL + '";</script>'
  95. # 计算md5
  96. def make_md5(data):
  97. md = hashlib.md5()
  98. md.update(data.encode('utf-8'))
  99. return md.hexdigest()
  100. # 获取用户信息
  101. def getUserInfo(params):
  102. params["do"] = "user.getInfo"
  103. params["appid"] = SSO_APPID
  104. params["_time"] = int(time.time())
  105. sort_params = sorted(params.items())
  106. params = {}
  107. for value in sort_params:
  108. params[value[0]] = value[1]
  109. params["sig"] = make_md5(urlencode(params) + SSO_APPTOKEN) # 签名
  110. url = SSO_URL + "cmsapi.php"
  111. resp = requests.get(url, params)
  112. return json.loads(resp.text)
  113. def checkCookie(request):
  114. # 获取http参数
  115. if request.method == "GET":
  116. sso_uid = 0
  117. _sso_uid = request.args.get('sso_uid')
  118. if _sso_uid != None:
  119. sso_uid = int(_sso_uid)
  120. sso_token = request.args.get('sso_token')
  121. elif request.method == "POST":
  122. sso_uid = 0
  123. _sso_uid = request.form.get("sso_uid")
  124. if _sso_uid != None:
  125. sso_uid = int(_sso_uid)
  126. sso_token = request.form.get("sso_token")
  127. # 获取sso信息有就保存
  128. if sso_uid != None and sso_token != None and sso_uid != 0 and len(sso_token) > 0:
  129. session["sso_uid"] = sso_uid
  130. session["sso_token"] = sso_token
  131. # 从session中获取sso信息
  132. ck_uid = session.get("sso_uid")
  133. ck_token = session.get("sso_token")
  134. if ck_uid == None or ck_token == None or ck_uid == 0 or len(ck_token) == 0:
  135. return False
  136. # sso信息未过期则不需要验证
  137. sso_info = gSsoManager.get(ck_uid)
  138. if sso_info != None:
  139. if sso_info["sso_token"] == ck_token:
  140. return True
  141. return False
  142. # # 丢弃
  143. # # 每次请求都验证用户信息太慢了
  144. # params = {"sso_uid": ck_uid, "sso_token": ck_token}
  145. # rets = getUserInfo(params)
  146. # if rets == None:
  147. # return False
  148. # if rets["ret"] == -200:
  149. # print(u"不信任的主机,请添加白名单")
  150. # return False
  151. # if rets["ret"] != 1:
  152. # return False
  153. # rets_data = rets.get("data")
  154. # if rets_data == None:
  155. # return False
  156. # rets_data_uid = rets_data.get("uid")
  157. # if rets_data_uid == None:
  158. # return False
  159. # return True
  160. @app.before_request
  161. def before_request():
  162. g.db = connect_db()
  163. if request.path != "/sso" and (not checkCookie(request)):
  164. return redirect_sso()
  165. @app.after_request
  166. def after_request(response):
  167. if g.db != None:
  168. g.db.close()
  169. g.db = None
  170. return response
  171. # sso回调接口
  172. @app.route('/sso', methods=['GET', 'POST'])
  173. def sso():
  174. return do_sso(request)
  175. def do_sso(request):
  176. if request.method == "GET":
  177. sso_uid = int(request.args.get('sso_uid'))
  178. sso_token = request.args.get('sso_token')
  179. elif request.method == "POST":
  180. sso_uid = int(request.form.get("sso_uid"))
  181. sso_token = request.form.get("sso_token")
  182. # 记录sso信息
  183. gSsoManager[sso_uid] = {
  184. "sso_uid": sso_uid, "sso_token": sso_token, "update_time": int(time.time())}
  185. params = urlparse.urlparse(request.url).query
  186. return redirect(gUrl + "?" + params)
  187. # 登录
  188. @app.route('/login', methods=['GET', 'POST'])
  189. def login():
  190. return do_login(request)
  191. # 主页
  192. @app.route('/', methods=['GET', 'POST'])
  193. def index():
  194. return render_template("index.html")
  195. # 控制
  196. @app.route('/jump/hosts', methods=['GET', 'POST'])
  197. def hostlist():
  198. return do_hostlist(request)
  199. @app.route('/jump/users', methods=['GET', 'POST'])
  200. def userlist():
  201. return do_userlist(request)
  202. @app.route('/jump/user/add', methods=['GET', 'POST'])
  203. def add_user():
  204. return do_add_user(request)
  205. @app.route('/jump/user/del', methods=['GET', 'POST'])
  206. def del_user():
  207. return do_del_user(request)
  208. @app.route('/jump/user/modify', methods=['GET', 'POST'])
  209. def modify_user():
  210. return do_modify_user(request)
  211. @app.route('/jump/user/hosts', methods=['GET', 'POST'])
  212. def userhostlist():
  213. return do_userhostlist(request)
  214. @app.route('/jump/host/add', methods=['GET', 'POST'])
  215. def add_host():
  216. return do_add_host(request)
  217. @app.route('/jump/host/del', methods=['GET', 'POST'])
  218. def del_host():
  219. return do_del_host(request)
  220. @app.route('/jump/host/adduser', methods=['GET', 'POST'])
  221. def host_adduser():
  222. return do_host_adduser(request)
  223. @app.route('/jump/host/deluser', methods=['GET', 'POST'])
  224. def host_deluser():
  225. return do_host_deluser(request)
  226. @app.route('/jump/host/modifyuser', methods=['GET', 'POST'])
  227. def host_modifyuser():
  228. return do_host_modifyuser(request)
  229. @app.route('/jump/host/users', methods=['GET', 'POST'])
  230. def hostuserlist():
  231. return do_hostuserlist(request)
  232. @app.route('/jump/hostuser', methods=['GET', 'POST'])
  233. def hostuser():
  234. return do_hostuserall(request)
  235. def do_login(request):
  236. if request.method == "GET":
  237. username = request.args.get('username')
  238. password = request.args.get('password')
  239. elif request.method == "POST":
  240. username = request.form.get("username") or "admin"
  241. password = request.form.get("password") or "123456"
  242. print("login username:%s password:%s" % (username, password))
  243. resp = {}
  244. resp["msg"] = "ok"
  245. resp["code"] = 200
  246. resp["user"] = username
  247. resp["sessionkey"] = "cookie-666"
  248. return json.dumps(resp)
  249. # get主机列表
  250. def do_hostlist(request):
  251. hosts = g.db.execute("select id,name,ip,port,desc,date from hosts where isdelete=0;").fetchall()
  252. resp = []
  253. for host in hosts:
  254. res = {}
  255. res["id"] = host[0]
  256. res["name"] = host[1]
  257. res["ip"] = host[2]
  258. res["port"] = host[3]
  259. res["desc"] = host[4]
  260. res["ctime"] = host[5]
  261. resp.append(res)
  262. return json.dumps(resp)
  263. # 获取用户列表
  264. def do_userlist(request):
  265. users = g.db.execute("select id,name,sudo,desc,date from users where isdelete=0;").fetchall()
  266. resp = []
  267. for user in users:
  268. res = {}
  269. res["id"] = user[0]
  270. res["name"] = user[1]
  271. res["sudo"] = user[2]
  272. res["desc"] = user[3]
  273. res["ctime"] = user[4]
  274. resp.append(res)
  275. return json.dumps(resp)
  276. # 添加用户
  277. def do_add_user(request):
  278. if request.method == "GET":
  279. name = request.args.get('name')
  280. desc = request.args.get('desc')
  281. elif request.method == "POST":
  282. name = request.form["name"]
  283. desc = request.form["desc"]
  284. ret = g.db.execute("select count(1) from users where name='%s'" % name).fetchone()
  285. if (len(ret) > 0 and ret[0]) >= 1:
  286. return "user %s exists" % name
  287. status, output = exec_command_output("sudo sh %s add %s \"%s\"" % (
  288. gManagerUserShellFile, name, gDefaultInitPassword))
  289. if status != 0:
  290. print("output=%s" % output)
  291. return "error %s" % output
  292. # 新增用户 sql
  293. g.db.execute("insert into users(name,desc) values('%s',\"%s\")" %
  294. (name, desc))
  295. g.db.commit()
  296. return "ok"
  297. # 删除用户
  298. def do_del_user(request):
  299. if request.method == "GET":
  300. username = request.args.get('name')
  301. elif request.method == "POST":
  302. username = request.form["name"]
  303. else:
  304. return "invalid request for del user"
  305. status, output = exec_command_output(
  306. "sudo sh %s del %s" % (gManagerUserShellFile, username))
  307. if status != 0:
  308. print("output=%s" % output)
  309. return "error %s" % output
  310. g.db.execute("delete from users where name='%s'" % username)
  311. g.db.execute("delete from hostuser where username='%s'" % username)
  312. g.db.commit()
  313. return "del user %s ok" % username
  314. # 修改用户
  315. def do_modify_user(request):
  316. if request.method == "GET":
  317. username = request.args.get('username')
  318. sudo = int(request.args.get('sudo'))
  319. desc = request.args.get('desc')
  320. elif request.method == "POST":
  321. username = request.form["username"]
  322. sudo = int(request.form["sudo"])
  323. desc = request.form["desc"]
  324. else:
  325. return "invalid request for user"
  326. # check param
  327. if sudo != 0 and sudo != 1:
  328. return "invalid request sudo:%d param" % sudo
  329. # 检查
  330. users = g.db.execute("select sudo,desc from users where name='%s'" % username).fetchall()
  331. if len(users) == 0:
  332. print("user(%s) not exitst" % username)
  333. return "user(%s) not exitst" % username
  334. user = users[0]
  335. user_sudo = user[0]
  336. user_desc = user[1]
  337. change = False # 是否需要修改
  338. opParam = "sudo" # 操作类型 sudo / unsudo
  339. if sudo == 0:
  340. opParam = "unsudo"
  341. if sudo != user_sudo:
  342. change = True
  343. # 处理sudo权限
  344. status, output = exec_command_output(
  345. "sudo sh manager_user.sh %s %s" % (opParam, username))
  346. if status != 0:
  347. print("%s user user(%s) failed! => output=%s" %
  348. (opParam, username, output))
  349. return "error: %s user user(%s) failed! => output=%s" % (opParam, username, output)
  350. if desc != user_desc:
  351. change = True
  352. # 记录在数据库中
  353. if change:
  354. print("update users set sudo=%d,desc=\"%s\" where name='%s'" %
  355. (sudo, desc, username))
  356. g.db.execute("update users set sudo=%d,desc=\"%s\" where name='%s'" % (
  357. sudo, desc, username))
  358. g.db.commit()
  359. print("modify user:%s successful [output: %s]" % (username, output))
  360. return "modify user:%s successful [output: %s]" % (username, output)
  361. # 添加主机
  362. def do_add_host(request):
  363. if request.method == "GET":
  364. name = request.args.get('name')
  365. ip = request.args.get('host')
  366. port = int(request.args.get('port'))
  367. desc = request.args.get('desc')
  368. elif request.method == "POST":
  369. name = request.form["name"]
  370. ip = request.form["host"]
  371. port = int(request.form["port"])
  372. desc = request.form["desc"]
  373. ret = g.db.execute(
  374. "select count(1) from hosts where name='%s' or ip='%s'" % (name, ip)).fetchone()
  375. if (len(ret) > 0 and ret[0]) >= 1:
  376. return "alias name(%s) or ip(%s) is exists" % (name, ip)
  377. # 新增用户 sql
  378. g.db.execute("insert into hosts(name,ip,port,desc) values('%s','%s',%d,'%s')" % (
  379. name, ip, port, desc))
  380. g.db.execute("insert into hostuser(hostname,username,sudo) values('%s','%s','%d')" % (
  381. name, gDefaultSSHAdmin, 1))
  382. g.db.commit()
  383. return "add host %s:%s ok" % (name, ip)
  384. # 删除主机
  385. def do_del_host(request):
  386. if request.method == "GET":
  387. hostname = request.args.get('name')
  388. ip = request.args.get('host')
  389. elif request.method == "POST":
  390. hostname = request.form["name"]
  391. ip = request.form["host"]
  392. else:
  393. return "invalid request for del host"
  394. g.db.execute("delete from hosts where name='%s' and ip='%s'" %
  395. (hostname, ip))
  396. g.db.execute("delete from hostuser where hostname='%s'" % hostname)
  397. g.db.commit()
  398. return "delete host %s:%s ok" % (hostname, ip)
  399. # 主机上添加用户
  400. def do_host_adduser(request):
  401. if request.method == "GET":
  402. hostname = request.args.get('hostname')
  403. username = request.args.get('username')
  404. elif request.method == "POST":
  405. hostname = request.form["hostname"]
  406. username = request.form["username"]
  407. else:
  408. return "invalid request for add user to host"
  409. # 检查
  410. ret = g.db.execute("select count(1) from hostuser where hostname='%s' and username='%s'" % (
  411. hostname, username)).fetchone()
  412. if (len(ret) > 0 and ret[0]) >= 1:
  413. print("user(%s) exitst on host(%s)" % (username, hostname))
  414. return "user(%s) exitst on host(%s)" % (username, hostname)
  415. # 检查
  416. hostips = g.db.execute("select ip,port from hosts where name='%s'" % (hostname)).fetchone()
  417. if hostips == None:
  418. print("host(%s) not exitst on hosts" % hostname)
  419. return "host(%s) not exitst on hosts" % hostname
  420. hostip = hostips[0]
  421. hostport = int(hostips[1])
  422. # 同步控制文件
  423. sync_remote_control_file(hostip, hostport)
  424. # 获取公钥
  425. status, publicSshRsaKey = exec_command_output(
  426. "sudo cat /home/%s/.ssh/id_rsa.pub" % username)
  427. if status != 0:
  428. print("cat user(%s) id_rsa.pub failed!", username)
  429. return "error %s" % publicSshRsaKey
  430. print("ssh %s@%s -p%d sudo sh .manager_user.sh add %s %s \"\"%s\"\"" %
  431. (gDefaultSSHAdmin, hostip, hostport, username, gDefaultInitPassword, publicSshRsaKey))
  432. # 主机上新建用户
  433. status, output = exec_command_output("ssh %s@%s -p%d sudo sh .manager_user.sh add %s %s \"\"%s\"\"" % (
  434. gDefaultSSHAdmin, hostip, hostport, username, gDefaultInitPassword, publicSshRsaKey))
  435. if status != 0:
  436. print("remote add user host(%s) user(%s) failed! => output=%s" %
  437. (hostname, username, output))
  438. return "error: remote add user host(%s) user(%s) failed! => output=%s" % (hostname, username, output)
  439. # 记录在数据库中
  440. g.db.execute("insert into hostuser(hostname,username) values('%s','%s')" % (
  441. hostname, username)).fetchone()
  442. g.db.commit()
  443. print("host remote =>> add user:%s to host:%s successful [output: %s]" % (
  444. username, hostname, output))
  445. return "host remote =>> add user:%s to host:%s successful" % (username, hostname)
  446. # 主机上删除用户
  447. def do_host_deluser(request):
  448. if request.method == "GET":
  449. hostname = request.args.get('hostname')
  450. username = request.args.get('username')
  451. elif request.method == "POST":
  452. hostname = request.form["hostname"]
  453. username = request.form["username"]
  454. else:
  455. return "invalid request for add user to host"
  456. # 检查
  457. ret = g.db.execute("select count(1) from hostuser where hostname='%s' and username='%s'" % (
  458. hostname, username)).fetchone()
  459. if (len(ret) > 0 and ret[0]) == 0:
  460. print("user(%s) not exitst on host(%s)" % (username, hostname))
  461. return "user(%s) not exitst on host(%s)" % (username, hostname)
  462. # 检查
  463. hostips = g.db.execute("select ip,port from hosts where name='%s'" % (hostname)).fetchone()
  464. if hostips == None:
  465. print("host(%s) not exitst on hosts" % hostname)
  466. return "host(%s) not exitst on hosts" % hostname
  467. hostip = hostips[0]
  468. hostport = int(hostips[1])
  469. # 同步控制文件
  470. sync_remote_control_file(hostip, hostport)
  471. # 主机上新建用户
  472. status, output = exec_command_output(
  473. "ssh %s@%s -p%d sudo sh .manager_user.sh del %s" % (gDefaultSSHAdmin, hostip, hostport, username))
  474. if status != 0:
  475. print("remote del user host(%s) user(%s) failed! => output=%s" %
  476. (hostname, username, output))
  477. return "error: remote del user host(%s) user(%s) failed! => output=%s" % (hostname, username, output)
  478. # 记录在数据库中
  479. g.db.execute("delete from hostuser where hostname='%s' and username='%s'" % (
  480. hostname, username))
  481. g.db.commit()
  482. print("host remote =>> del user:%s from host:%s successful [output: %s]" % (
  483. username, hostname, output))
  484. return "host remote =>> del user:%s from host:%s successful" % (username, hostname)
  485. # 主机上修改用户信息
  486. def do_host_modifyuser(request):
  487. if request.method == "GET":
  488. hostname = request.args.get('hostname')
  489. username = request.args.get('username')
  490. sudo = int(request.args.get('sudo'))
  491. desc = request.args.get('desc')
  492. elif request.method == "POST":
  493. hostname = request.form["hostname"]
  494. username = request.form["username"]
  495. sudo = int(request.form["username"])
  496. desc = request.form["desc"]
  497. else:
  498. return "invalid request for add user to host"
  499. # 检查
  500. hostusers = g.db.execute("select sudo,desc from hostuser where hostname='%s' and username='%s' and isdelete=0" % (
  501. hostname, username)).fetchone()
  502. if len(hostusers) > 0 and hostusers[0] != None:
  503. print("user(%s) not exitst on host(%s)" % (username, hostname))
  504. return "user(%s) not exitst on host(%s)" % (username, hostname)
  505. hostuser = hostusers[0]
  506. user_sudo = hostuser[0]
  507. user_desc = hostuser[1]
  508. change = False
  509. opParam = "sudo"
  510. if sudo == 0:
  511. opParam = "unsudo"
  512. if sudo != user_sudo:
  513. change = True
  514. # 检查
  515. hostips = g.db.execute("select ip,port from hosts where name='%s'" % (hostname)).fetchone()
  516. if hostips == None:
  517. print("host(%s) not exitst on hosts" % hostname)
  518. return "host(%s) not exitst on hosts" % hostname
  519. hostip = hostips[0]
  520. hostport = int(hostips[1])
  521. # 主机上修改sudo
  522. status, output = exec_command_output(
  523. "ssh %s@%s -p%d sudo sh .manager_user.sh %s %s" % (gDefaultSSHAdmin, hostip, hostport, opParam, username))
  524. if status != 0:
  525. print("remote %s user host(%s) user(%s) failed! => output=%s" %
  526. (opParam, hostname, username, output))
  527. return "error: remote %s user host(%s) user(%s) failed! => output=%s" % (opParam, hostname, username, output)
  528. if desc != user_desc:
  529. change = True
  530. if change:
  531. # 记录在数据库中
  532. g.db.execute("update hostuser set sudo=%d,desc=%s where hostname='%s' and username='%s'" % (
  533. sudo, desc, hostname, username))
  534. g.db.commit()
  535. print("host remote =>> %s user:%s from host:%s successful [output: %s]" % (
  536. opParam, username, hostname, output))
  537. return "host remote =>> %s user:%s from host:%s successful [output: %s]" % (opParam, username, hostname, output)
  538. # 获取用户所有的主机列表
  539. def do_userhostlist(request):
  540. if request.method == "GET":
  541. username = request.args.get('username')
  542. elif request.method == "POST":
  543. username = request.form["username"]
  544. else:
  545. return "invalid request for getting user host list"
  546. 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()
  547. resp = []
  548. for host in hosts:
  549. res = {}
  550. res["id"] = host[0]
  551. res["name"] = host[1]
  552. res["ip"] = host[2]
  553. res["port"] = host[3]
  554. res["desc"] = host[4]
  555. res["ctime"] = host[5]
  556. resp.append(res)
  557. return json.dumps(resp)
  558. # 获取主机上的用户列表
  559. def do_hostuserlist(request):
  560. if request.method == "GET":
  561. hostname = request.args.get('hostname')
  562. elif request.method == "POST":
  563. hostname = request.form["hostname"]
  564. else:
  565. return "invalid request for getting host user list"
  566. users = g.db.execute(
  567. "select id,username,sudo,date from hostuser where isdelete=0 and hostname='%s'" % hostname).fetchall()
  568. resp = []
  569. for user in users:
  570. res = {}
  571. res["id"] = user[0]
  572. res["username"] = user[1]
  573. res["sudo"] = user[2]
  574. res["ctime"] = user[3]
  575. resp.append(res)
  576. return json.dumps(resp)
  577. # 获取所有的用户主机列表
  578. def do_hostuserall(request):
  579. users = g.db.execute(
  580. "select id,hostname,username,sudo,date from hostuser where isdelete=0").fetchall()
  581. resp = []
  582. for user in users:
  583. res = {}
  584. res["id"] = user[0]
  585. res["hostname"] = user[1]
  586. res["username"] = user[2]
  587. res["sudo"] = user[3]
  588. res["ctime"] = user[4]
  589. resp.append(res)
  590. return json.dumps(resp)
  591. # 连接数据库
  592. def connect_db():
  593. return sqlite3.connect(gSqlite3File)
  594. # 初始化表
  595. def init_db():
  596. # 连接数据库
  597. conn = connect_db()
  598. if conn == None:
  599. sys.exit(1)
  600. # 初始化用户表
  601. conn.execute(gUsersTableSql)
  602. # 初始化主机表
  603. conn.execute(gHostsTableSql)
  604. # 创建主机用户表
  605. conn.execute(gHostUserSql)
  606. # sso本地管理
  607. def sso_timeout():
  608. # 当前时间戳
  609. nowtime = int(time.time())
  610. # 需求删除的key
  611. delkeys = []
  612. for sso_uid, sso_info in gSsoManager.items():
  613. if nowtime - sso_info["update_time"] >= SSO_EXPIRE_TIMEOUT:
  614. delkeys.append(sso_uid)
  615. # 删除key
  616. for key in delkeys:
  617. del gSsoManager[key]
  618. # 循环定时器
  619. Timer(SSO_TIMER_PERIOD, sso_timeout).start()
  620. def main():
  621. # 解析命令行
  622. parse_cmd()
  623. # 初始化db
  624. init_db()
  625. # 启动sso定时器 秒
  626. Timer(SSO_TIMER_PERIOD, sso_timeout).start()
  627. # 启动HTTP服务
  628. app.run(
  629. host=gHost,
  630. port=gPort,
  631. debug=gDebug
  632. )
  633. # 入口
  634. if __name__ == '__main__':
  635. main()