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

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