Browse Source

cmd args\import logging

master
牛批的一批 5 years ago
parent
commit
a0a4921def
  1. 155
      server/jumpserver.py

155
server/jumpserver.py

@ -1,9 +1,10 @@
# -*- coding: UTF-8 -*- # -*- coding: UTF-8 -*-
import argparse
import sys import sys
import getopt
import os import os
import time import time
import logging
from threading import Timer from threading import Timer
import subprocess import subprocess
import sqlite3 import sqlite3
@ -16,16 +17,15 @@ import requests
from flask import request, Flask, redirect, session, render_template, g from flask import request, Flask, redirect, session, render_template, g
from flask_cors import CORS from flask_cors import CORS
# 启动flask
app = Flask(__name__, app = Flask(__name__,
static_folder="/home/daniel/vue-admin/dist/static", static_folder="/home/daniel/vue-admin/dist/static",
template_folder="/home/daniel/vue-admin/dist") template_folder="/home/daniel/vue-admin/dist")
app.config['SECRET_KEY'] = os.urandom(24) app.config['SECRET_KEY'] = os.urandom(24)
CORS(app) CORS(app)
# http bind
gHost = ""
gPort = 0
gDebug = 0
# 命令行参数
gCmdArgs = {}
# 数据库文件 # 数据库文件
gSqlite3File = "/usr/local/jumpserver/jumpserver.db" gSqlite3File = "/usr/local/jumpserver/jumpserver.db"
@ -55,39 +55,35 @@ gUrl = "http://192.168.1.44:8080/"
# sso管理 # sso管理
gSsoManager = {} gSsoManager = {}
# sso定时器执行周期 # sso定时器执行周期
SSO_TIMER_PERIOD = 5*60
SSO_TIMER_PERIOD = 5 * 60
# sso过期时间 # sso过期时间
SSO_EXPIRE_TIMEOUT = 24*60*60
SSO_EXPIRE_TIMEOUT = 24 * 60 * 60
# 解析命令行 # 解析命令行
def parse_cmd(): 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)
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 # 主页url
global gUrl 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( status, output = exec_command_output(
"scp -P %d manager_user.sh %s@%s:.manager_user.sh" % (port, gDefaultSSHAdmin, host)) "scp -P %d manager_user.sh %s@%s:.manager_user.sh" % (port, gDefaultSSHAdmin, host))
if status != 0: if status != 0:
print("sync_remote_control_file error %s" % output)
logging.error("sync_remote_control_file error %s", output)
return -1 return -1
return 0 return 0
@ -181,7 +177,7 @@ def checkCookie(request):
# if rets == None: # if rets == None:
# return False # return False
# if rets["ret"] == -200: # if rets["ret"] == -200:
# print(u"不信任的主机,请添加白名单")
# logging.error(u"不信任的主机,请添加白名单")
# return False # return False
# if rets["ret"] != 1: # if rets["ret"] != 1:
# return False # return False
@ -203,7 +199,7 @@ def before_request():
# 连接db并标志 # 连接db并标志
g.db = connect_db() g.db = connect_db()
g.isconnect_db = True g.isconnect_db = True
# 处理请求后回调 # 处理请求后回调
@app.after_request @app.after_request
@ -304,7 +300,7 @@ def do_login(request):
username = request.form.get("username") or "admin" username = request.form.get("username") or "admin"
password = request.form.get("password") or "123456" 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 = {}
resp["msg"] = "ok" resp["msg"] = "ok"
resp["code"] = 200 resp["code"] = 200
@ -343,6 +339,7 @@ def do_userlist(request):
resp.append(res) resp.append(res)
return json.dumps(resp) return json.dumps(resp)
# 添加用户 # 添加用户
def do_add_user(request): def do_add_user(request):
if request.method == "GET": if request.method == "GET":
@ -359,12 +356,12 @@ def do_add_user(request):
status, output = exec_command_output("sudo sh %s add %s \"%s\"" % ( status, output = exec_command_output("sudo sh %s add %s \"%s\"" % (
gManagerUserShellFile, name, gDefaultInitPassword)) gManagerUserShellFile, name, gDefaultInitPassword))
if status != 0: if status != 0:
print("output=%s" % output)
logging.error("output=%s", output)
return "error %s" % output return "error %s" % output
# 新增用户 sql # 新增用户 sql
g.db.execute("insert into users(name,desc) values('%s',\"%s\")" % g.db.execute("insert into users(name,desc) values('%s',\"%s\")" %
(name, desc))
(name, desc))
g.db.commit() g.db.commit()
return "ok" return "ok"
@ -381,7 +378,7 @@ def do_del_user(request):
status, output = exec_command_output( status, output = exec_command_output(
"sudo sh %s del %s" % (gManagerUserShellFile, username)) "sudo sh %s del %s" % (gManagerUserShellFile, username))
if status != 0: if status != 0:
print("output=%s" % output)
logging.error("output=%s", output)
return "error %s" % output return "error %s" % output
g.db.execute("delete from users where name='%s'" % username) 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() users = g.db.execute("select sudo,desc from users where name='%s'" % username).fetchall()
if len(users) == 0: if len(users) == 0:
print("user(%s) not exitst" % username)
logging.error("user(%s) not exitst", username)
return "user(%s) not exitst" % username return "user(%s) not exitst" % username
user = users[0] user = users[0]
@ -430,8 +427,7 @@ def do_modify_user(request):
status, output = exec_command_output( status, output = exec_command_output(
"sudo sh manager_user.sh %s %s" % (opParam, username)) "sudo sh manager_user.sh %s %s" % (opParam, username))
if status != 0: 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) return "error: %s user user(%s) failed! => output=%s" % (opParam, username, output)
if len(password) > 0: if len(password) > 0:
@ -440,8 +436,7 @@ def do_modify_user(request):
status, output = exec_command_output( status, output = exec_command_output(
"sudo sh manager_user.sh %s %s" % (opParam, username)) "sudo sh manager_user.sh %s %s" % (opParam, username))
if status != 0: 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) return "error: %s user user(%s) failed! => output=%s" % (opParam, username, output)
if desc != user_desc: if desc != user_desc:
@ -449,13 +444,11 @@ def do_modify_user(request):
# 记录在数据库中 # 记录在数据库中
if change: 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() 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) return "modify user:%s successful [output: %s]" % (username, output)
@ -498,7 +491,7 @@ def do_del_host(request):
return "invalid request for del host" return "invalid request for del host"
g.db.execute("delete from hosts where name='%s' and ip='%s'" % 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.execute("delete from hostuser where hostname='%s'" % hostname)
g.db.commit() g.db.commit()
return "delete host %s:%s ok" % (hostname, ip) 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'" % ( ret = g.db.execute("select count(1) from hostuser where hostname='%s' and username='%s'" % (
hostname, username)).fetchone() hostname, username)).fetchone()
if (len(ret) > 0 and ret[0]) >= 1: 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) return "user(%s) exitst on host(%s)" % (username, hostname)
# 检查 # 检查
hostips = g.db.execute("select ip,port from hosts where name='%s'" % (hostname)).fetchone() hostips = g.db.execute("select ip,port from hosts where name='%s'" % (hostname)).fetchone()
if hostips == None: 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 return "host(%s) not exitst on hosts" % hostname
hostip = hostips[0] hostip = hostips[0]
hostport = int(hostips[1]) hostport = int(hostips[1])
@ -537,17 +530,15 @@ def do_host_adduser(request):
status, publicSshRsaKey = exec_command_output( status, publicSshRsaKey = exec_command_output(
"sudo cat /home/%s/.ssh/id_rsa.pub" % username) "sudo cat /home/%s/.ssh/id_rsa.pub" % username)
if status != 0: 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 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\"\"" % ( 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)) gDefaultSSHAdmin, hostip, hostport, username, gDefaultInitPassword, publicSshRsaKey))
if status != 0: 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) 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() hostname, username)).fetchone()
g.db.commit() 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) 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'" % ( ret = g.db.execute("select count(1) from hostuser where hostname='%s' and username='%s'" % (
hostname, username)).fetchone() hostname, username)).fetchone()
if (len(ret) > 0 and ret[0]) == 0: 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) return "user(%s) not exitst on host(%s)" % (username, hostname)
# 检查 # 检查
hostips = g.db.execute("select ip,port from hosts where name='%s'" % (hostname)).fetchone() hostips = g.db.execute("select ip,port from hosts where name='%s'" % (hostname)).fetchone()
if hostips == None: 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 return "host(%s) not exitst on hosts" % hostname
hostip = hostips[0] hostip = hostips[0]
hostport = int(hostips[1]) hostport = int(hostips[1])
@ -593,8 +583,7 @@ def do_host_deluser(request):
status, output = exec_command_output( status, output = exec_command_output(
"ssh %s@%s -p%d sudo sh .manager_user.sh del %s" % (gDefaultSSHAdmin, hostip, hostport, username)) "ssh %s@%s -p%d sudo sh .manager_user.sh del %s" % (gDefaultSSHAdmin, hostip, hostport, username))
if status != 0: 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) 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)) hostname, username))
g.db.commit() 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) return "host remote =>> del user:%s from host:%s successful" % (username, hostname)
# 主机上修改用户信息 # 主机上修改用户信息
def do_host_modifyuser(request): def do_host_modifyuser(request):
if request.method == "GET": 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" % ( hostusers = g.db.execute("select sudo,desc from hostuser where hostname='%s' and username='%s' and isdelete=0" % (
hostname, username)).fetchone() hostname, username)).fetchone()
if len(hostusers) > 0 and hostusers[0] != None: 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) return "user(%s) not exitst on host(%s)" % (username, hostname)
hostuser = hostusers[0] 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() hostips = g.db.execute("select ip,port from hosts where name='%s'" % (hostname)).fetchone()
if hostips == None: 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 return "host(%s) not exitst on hosts" % hostname
hostip = hostips[0] hostip = hostips[0]
hostport = int(hostips[1]) hostport = int(hostips[1])
@ -653,19 +642,20 @@ def do_host_modifyuser(request):
status, output = exec_command_output( status, output = exec_command_output(
"ssh %s@%s -p%d sudo sh .manager_user.sh %s %s" % (gDefaultSSHAdmin, hostip, hostport, opParam, username)) "ssh %s@%s -p%d sudo sh .manager_user.sh %s %s" % (gDefaultSSHAdmin, hostip, hostport, opParam, username))
if status != 0: 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: if len(password) > 0:
# 主机上修改密码 # 主机上修改密码
opParam = "passwd" opParam = "passwd"
status, output = exec_command_output( 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: 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: if desc != user_desc:
change = True change = True
@ -676,8 +666,7 @@ def do_host_modifyuser(request):
sudo, desc, hostname, username)) sudo, desc, hostname, username))
g.db.commit() 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) return "host remote =>> modify user:%s from host:%s successful [output: %s]" % (username, hostname, output)
@ -690,7 +679,8 @@ def do_userhostlist(request):
else: else:
return "invalid request for getting user host list" 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 = [] resp = []
for host in hosts: for host in hosts:
res = {} res = {}
@ -779,8 +769,16 @@ def sso_timeout():
# 循环定时器 # 循环定时器
Timer(SSO_TIMER_PERIOD, sso_timeout).start() 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(): def main():
# 初始化日志
init_log()
# 解析命令行 # 解析命令行
parse_cmd() parse_cmd()
@ -792,12 +790,11 @@ def main():
# 启动HTTP服务 # 启动HTTP服务
app.run( app.run(
host=gHost,
port=gPort,
debug=gDebug
host=gCmdArgs.host,
port=gCmdArgs.port,
debug=gCmdArgs.debug
) )
# 入口 # 入口
if __name__ == '__main__': if __name__ == '__main__':
main() main()
Loading…
Cancel
Save