diff --git a/server/jumpserver.py b/server/jumpserver.py index 4f44769..5fa7506 100644 --- a/server/jumpserver.py +++ b/server/jumpserver.py @@ -1,9 +1,10 @@ # -*- coding: UTF-8 -*- +import argparse import sys -import getopt import os import time +import logging from threading import Timer import subprocess import sqlite3 @@ -16,16 +17,15 @@ 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) -# http bind -gHost = "" -gPort = 0 -gDebug = 0 +# 命令行参数 +gCmdArgs = {} # 数据库文件 gSqlite3File = "/usr/local/jumpserver/jumpserver.db" @@ -55,39 +55,35 @@ gUrl = "http://192.168.1.44:8080/" # sso管理 gSsoManager = {} # sso定时器执行周期 -SSO_TIMER_PERIOD = 5*60 +SSO_TIMER_PERIOD = 5 * 60 # sso过期时间 -SSO_EXPIRE_TIMEOUT = 24*60*60 +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 -p -d ' % (sys.argv[0])) - sys.exit(0) - for opt, arg in opts: - if opt == '-H': - print('python3 %s -h -p -d ' % (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 -p -d ' % (sys.argv[0])) - sys.exit(0) + 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/" % (gHost, gPort) + gUrl = "http://%s:%d/" % (gCmdArgs.host, gCmdArgs.port) # 只有执行结果 @@ -105,7 +101,7 @@ 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) + logging.error("sync_remote_control_file error %s", output) return -1 return 0 @@ -181,7 +177,7 @@ def checkCookie(request): # if rets == None: # return False # if rets["ret"] == -200: - # print(u"不信任的主机,请添加白名单") + # logging.error(u"不信任的主机,请添加白名单") # return False # if rets["ret"] != 1: # return False @@ -203,7 +199,7 @@ def before_request(): # 连接db并标志 g.db = connect_db() g.isconnect_db = True - + # 处理请求后回调 @app.after_request @@ -304,7 +300,7 @@ def do_login(request): username = request.form.get("username") or "admin" password = request.form.get("password") or "123456" - print("login username:%s password:%s" % (username, password)) + logging.info("login username:%s password:%s", username, password) resp = {} resp["msg"] = "ok" resp["code"] = 200 @@ -343,6 +339,7 @@ def do_userlist(request): resp.append(res) return json.dumps(resp) + # 添加用户 def do_add_user(request): if request.method == "GET": @@ -359,12 +356,12 @@ def do_add_user(request): status, output = exec_command_output("sudo sh %s add %s \"%s\"" % ( gManagerUserShellFile, name, gDefaultInitPassword)) if status != 0: - print("output=%s" % output) + logging.error("output=%s", output) return "error %s" % output # 新增用户 sql g.db.execute("insert into users(name,desc) values('%s',\"%s\")" % - (name, desc)) + (name, desc)) g.db.commit() return "ok" @@ -381,7 +378,7 @@ def do_del_user(request): status, output = exec_command_output( "sudo sh %s del %s" % (gManagerUserShellFile, username)) if status != 0: - print("output=%s" % output) + logging.error("output=%s", output) return "error %s" % output g.db.execute("delete from users where name='%s'" % username) @@ -412,7 +409,7 @@ def do_modify_user(request): # 检查 users = g.db.execute("select sudo,desc from users where name='%s'" % username).fetchall() if len(users) == 0: - print("user(%s) not exitst" % username) + logging.error("user(%s) not exitst", username) return "user(%s) not exitst" % username user = users[0] @@ -430,8 +427,7 @@ def do_modify_user(request): 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)) + 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: @@ -440,8 +436,7 @@ def do_modify_user(request): 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)) + 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: @@ -449,13 +444,11 @@ def do_modify_user(request): # 记录在数据库中 if change: - print("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)) + 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() - print("modify user:%s successful [output: %s]" % (username, output)) + logging.info("modify user:%s successful [output: %s]", username, output) return "modify user:%s successful [output: %s]" % (username, output) @@ -498,7 +491,7 @@ def do_del_host(request): return "invalid request for del host" g.db.execute("delete from hosts where name='%s' and ip='%s'" % - (hostname, ip)) + (hostname, ip)) g.db.execute("delete from hostuser where hostname='%s'" % hostname) g.db.commit() return "delete host %s:%s ok" % (hostname, ip) @@ -519,13 +512,13 @@ def do_host_adduser(request): 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: - print("user(%s) exitst on host(%s)" % (username, hostname)) + 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: - print("host(%s) not exitst on hosts" % hostname) + logging.error("host(%s) not exitst on hosts", hostname) return "host(%s) not exitst on hosts" % hostname hostip = hostips[0] hostport = int(hostips[1]) @@ -537,17 +530,15 @@ def do_host_adduser(request): 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) + logging.error("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)) + 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: - print("remote add user host(%s) user(%s) failed! => output=%s" % - (hostname, username, output)) + 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) # 记录在数据库中 @@ -555,8 +546,7 @@ def do_host_adduser(request): hostname, username)).fetchone() g.db.commit() - print("host remote =>> add user:%s to host:%s successful [output: %s]" % ( - username, hostname, output)) + 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) @@ -575,13 +565,13 @@ def do_host_deluser(request): 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: - print("user(%s) not exitst on host(%s)" % (username, hostname)) + 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: - print("host(%s) not exitst on hosts" % hostname) + logging.error("host(%s) not exitst on hosts", hostname) return "host(%s) not exitst on hosts" % hostname hostip = hostips[0] hostport = int(hostips[1]) @@ -593,8 +583,7 @@ def do_host_deluser(request): 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)) + 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) # 记录在数据库中 @@ -602,10 +591,10 @@ def do_host_deluser(request): hostname, username)) g.db.commit() - print("host remote =>> del user:%s from host:%s successful [output: %s]" % ( - username, hostname, output)) + 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": @@ -627,7 +616,7 @@ def do_host_modifyuser(request): 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: - print("user(%s) not exitst on host(%s)" % (username, hostname)) + logging.error("user(%s) not exitst on host(%s)", username, hostname) return "user(%s) not exitst on host(%s)" % (username, hostname) hostuser = hostusers[0] @@ -641,7 +630,7 @@ def do_host_modifyuser(request): # 检查 hostips = g.db.execute("select ip,port from hosts where name='%s'" % (hostname)).fetchone() if hostips == None: - print("host(%s) not exitst on hosts" % hostname) + logging.error("host(%s) not exitst on hosts", hostname) return "host(%s) not exitst on hosts" % hostname hostip = hostips[0] hostport = int(hostips[1]) @@ -653,19 +642,20 @@ def do_host_modifyuser(request): 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) + 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)) + "ssh %s@%s -p%d sudo sh .manager_user.sh %s %s %s" % ( + gDefaultSSHAdmin, hostip, hostport, opParam, username, password)) 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) + 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 @@ -676,8 +666,7 @@ def do_host_modifyuser(request): sudo, desc, hostname, username)) g.db.commit() - print("host remote =>> modify user:%s from host:%s successful [output: %s]" % ( - username, hostname, output)) + 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) @@ -690,7 +679,8 @@ def do_userhostlist(request): 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() + 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 = {} @@ -779,8 +769,16 @@ def sso_timeout(): # 循环定时器 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_log() + # 解析命令行 parse_cmd() @@ -792,12 +790,11 @@ def main(): # 启动HTTP服务 app.run( - host=gHost, - port=gPort, - debug=gDebug + host=gCmdArgs.host, + port=gCmdArgs.port, + debug=gCmdArgs.debug ) - # 入口 if __name__ == '__main__': main()