Commit 37c3a38b authored by tarak.li's avatar tarak.li

优化代码,场景测试

parent aedddc03
......@@ -4,22 +4,26 @@ import json
import re
import socket
import hashlib
import time
from pyDes import des, CBC, PAD_PKCS5
import binascii
import requests
from concurrent.futures import ThreadPoolExecutor
from tornado.escape import json_decode, json_encode
from tornado.concurrent import run_on_executor
import tornado.web
from app.base.controller import TPBaseHandler
from app.base.core_server import core_service_async_enc
from app.base.logger import *
from app.const import TP_PRIVILEGE_ASSET_CREATE, TPE_PARAM, TPE_OK, TPE_JSON_FORMAT, TP_AUTH_TYPE_PASSWORD, \
TP_AUTH_TYPE_PRIVATE_KEY, TPE_EXISTS, TPE_FAILED, TPE_NOT_EXISTS
from app.model import account
from app.model import host
from app.model import plugin
from app.model.plugin import free_host
# todo 间歇性 ERROR:tornado.application:Uncaught exception
def current_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
......@@ -34,6 +38,43 @@ def network_ip():
return ip
# 秘钥
KEY = 'mHAxsLYz'
def des_encrypt(s, key=None):
"""
DES 加密
:param s: 原始字符串
:return: 加密后字符串,16进制
"""
secret_key = key or KEY
iv = secret_key
k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
en = k.encrypt(s, padmode=PAD_PKCS5)
return binascii.b2a_hex(en)
def des_descrypt(s, key=None):
"""
DES 解密
:param s: 加密后的字符串,16进制
:return: 解密后的字符串
"""
secret_key = key or KEY
iv = secret_key
k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
de = k.decrypt(binascii.a2b_hex(s), padmode=PAD_PKCS5)
return de
def md5(str):
m = hashlib.md5()
b = str.encode(encoding='utf-8')
m.update(b)
return m.hexdigest()
class TPBasePluginHandler(TPBaseHandler):
"""
所有返回JSON数据的控制器均从本类继承,返回的数据格式一律包含三个字段:code/msg/data
......@@ -71,7 +112,7 @@ class TPBasePluginHandler(TPBaseHandler):
def get_payload(self):
log.i(self.request.body)
log.i('\n')
log.i("\n")
return json_decode(self.request.body)
def check_ip(self, props):
......@@ -83,7 +124,7 @@ class TPBasePluginHandler(TPBaseHandler):
def control_ip(self, ip):
items = ip.split(".")[:2]
if items == self.outer_ip.split(".")[:2] or items == self.local_ip.split(".")[:2]:
if ip == '127.0.0.1' or items == self.outer_ip.split(".")[:2] or items == self.local_ip.split(".")[:2]:
return True
else:
return False
......@@ -97,7 +138,9 @@ class TPBasePluginHandler(TPBaseHandler):
log.i('\n')
self.write(json_encode(_ret))
self.finish()
return
def param_get(self, props: dict, fields: list, default):
return [props.get(i) or default for i in fields]
@run_on_executor
def request_api(self, url, data=None, json=None):
......@@ -113,215 +156,165 @@ class TPBasePluginHandler(TPBaseHandler):
resp = requests.post(url, data=data, json=json, cookies=cookies)
return resp.json()
def query(self, table, field, filter):
return plugin.query_one(table, [field], filter).get(field, 0)
class UpdateHostHandler(TPBasePluginHandler):
def insert_host(self):
args = self.get_argument('args', None)
try:
args = json.loads(args)
except:
return TPE_PARAM
if len(args['ip']) == 0:
return TPE_PARAM
if args['id'] == -1:
err, info = host.add_host(self, args)
else:
err = host.update_host(self, args)
info = 0
return err, info
def insert_account(self):
args = self.get_argument('args', None)
if args is None:
return self.write_json(TPE_PARAM)
try:
args = json.loads(args)
except:
return self.write_json(TPE_JSON_FORMAT)
try:
host_id = int(args['host_id'])
acc_id = int(args['acc_id'])
except:
log.e('\n')
return self.write_json(TPE_PARAM)
try:
param = dict()
param['host_ip'] = args['param']['host_ip']
param['router_ip'] = args['param']['router_ip']
param['router_port'] = args['param']['router_port']
param['protocol_type'] = int(args['param']['protocol'])
param['protocol_port'] = int(args['param']['port'])
param['auth_type'] = int(args['param']['auth_type'])
param['username'] = args['param']['username'].strip()
param['password'] = args['param']['password']
param['pri_key'] = args['param']['pri_key'].strip()
param['username_prompt'] = args['param']['username_prompt'].strip()
param['password_prompt'] = args['param']['password_prompt'].strip()
except:
log.e('\n')
return self.write_json(TPE_PARAM)
if len(param['username']) == 0:
return self.write_json(TPE_PARAM)
if acc_id == -1:
# 新增账号
if param['auth_type'] == TP_AUTH_TYPE_PASSWORD and len(param['password']) == 0:
return self.write_json(TPE_PARAM)
elif param['auth_type'] == TP_AUTH_TYPE_PRIVATE_KEY and len(param['pri_key']) == 0:
return self.write_json(TPE_PARAM)
if acc_id == -1:
err, info = account.add_account(self, host_id, param)
else:
err = account.update_account(self, host_id, acc_id, param)
info = {}
return err, info
def generate_assets_num(self, ip):
class UpdateHostHandler(TPBasePluginHandler):
def generate_assets_num(self, ip, os_type):
data = ip.split('.')
data = ['%03d' % int(i) for i in data]
return ''.join(data)
assets_num = ''.join(data)
if os_type == 1:
assets_num = 'W' + assets_num
elif os_type == 2:
assets_num = 'L' + assets_num
return assets_num
@tornado.gen.coroutine
def post(self):
# todo 数据处理不同步
props = self.get_payload()
if not self.check_ip(props):
self.finish_json(1001, "IP不符合规范")
return
os_type = props.pop("os_type", 0)
ip = props.pop("ip", "")
username = props.pop("username", "")
password = props.pop("password", 0)
name = props.pop("name", "")
desc = props.pop("desc", "")
host_id = props.pop("host_id", 0)
app_id = props.pop("app_id", 0)
status = props.get("status", 0)
os_type, host_id, app_id, status = self.param_get(props, ['os_type', 'host_id', 'app_id', 'status'], 0)
ip, username, password, name, desc = self.param_get(props, ['ip', 'username', 'password', 'name', 'desc', ], '')
# “res”:1,“ec”:”0”,“msg”:”成功”
if not os_type or not ip or not username or not password:
self.finish_json(1001, "缺少必要参数异常")
return
assets_num = self.generate_assets_num(ip)
args = {"id": -1, "os_type": os_type, "ip": ip, "router_ip": "", "router_port": 0, "name": "",
"cid": assets_num,
"desc": ""}
args = json.dumps(args).encode()
self.request.arguments = {'args': [args]}
assets_num = self.generate_assets_num(ip, os_type)
# 添加主机
err, info = self.insert_host()
url = "http://127.0.0.1:7190/asset/update-host"
# 相同主机不允许重复添加
if err == TPE_EXISTS:
args = {"args": json.dumps(
{"id": -1, "os_type": os_type, "ip": ip, "router_ip": "", "router_port": 0, "name": name, "cid": assets_num,
"desc": desc}).encode()}
# 带信息带先插入
resp = yield self.request_api(url, args)
# {"code": 0, "message": "", "data": 7}
if resp.get("code") == 8:
self.finish_json(1003, "已存在主机,不可重复添加")
return
elif resp.get("code") != 0:
self.finish_json(1003, "添加主机异常")
return
code, ret_data = yield core_service_async_enc(password)
if code != TPE_OK:
return self.write_json(code)
host_id = resp.get("data")
host_id = info
args = {"host_id": host_id, "acc_id": -1,
"param": {"host_ip": ip, "router_ip": "", "router_port": 0, "protocol": 1, "port": 3389,
"auth_type": 1, "username": username, "password": ret_data, "pri_key": "",
"username_prompt": "", "password_prompt": ""}}
args = json.dumps(args).encode()
url = "http://127.0.0.1:7190/asset/update-account"
# 添加用户
self.request.arguments = {'args': [args]}
args = {"args": json.dumps({"host_id": host_id, "acc_id": -1,
"param": {"host_ip": ip, "router_ip": "", "router_port": 0,
"protocol": 1, "port": 3389, "auth_type": 1, "username": username,
"password": password, "pri_key": "", "username_prompt": "",
"password_prompt": ""}}).encode()}
err, info = self.insert_account()
# {"code": 0, "message": "", "data": 5}
# 带信息带先插入
resp = yield self.request_api(url, args)
if info > 0:
args = {"host_id": host_id, "name": name, "ip": ip, "remark": desc, "username": username,
"password": ret_data, "assets_num": assets_num, "os_type": os_type, "status": status}
plugin.add_remote_host(self, args)
if resp.get("code") != 0:
self.finish_json(1004, "添加服务器账户异常")
return
# acc_id = resp.get("data")
args = {"host_id": host_id, "name": name, "ip": ip, "remark": desc, "username": username,
"password": "", "assets_num": assets_num, "os_type": os_type, "status": status}
err, info = plugin.add_remote_host(self, args)
if err == TPE_OK:
self.finish_json(0, "成功")
else:
self.finish_json(1003, "设备添加异常")
self.finish_json(1002, "记录主机信息失败")
@tornado.gen.coroutine
def put(self):
props = self.get_payload()
log.i(props)
if not self.check_ip(props):
self.finish_json(1001, "IP不符合规范")
return
os_type = props.get("os_type", 0)
ip = props.get("ip", "")
username = props.get("username", "")
password = props.get("password", 0)
name = props.get("name", "")
desc = props.get("desc", "")
host_id = props.get("host_id", 0)
status = props.get("status", 0)
os_type, host_id, status = self.param_get(props, ['os_type', 'host_id', 'status'], 0)
ip, username, password, name, desc = self.param_get(props, ['ip', 'username', 'password', 'name', 'desc', ], '')
# “res”:1,“ec”:”0”,“msg”:”成功”
if not os_type or not ip or not username or not password:
if not os_type or not ip or not username:
self.finish_json(1001, "缺少必要参数异常")
return
args = {"os_type": os_type, "ip": ip, "username": username, "password": password, "name": name, "remark": desc,
assets_num = self.generate_assets_num(ip, os_type)
url = "http://127.0.0.1:7190/asset/update-host"
args = {"args": json.dumps(
{"id": host_id, "os_type": os_type, "ip": ip, "router_ip": "", "router_port": 0, "name": name,
"cid": assets_num, "desc": desc}).encode()}
# 带信息带先插入
resp = yield self.request_api(url, args)
# {"code": 0, "message": "", "data": 7}
if resp.get("code") == 8:
self.finish_json(1003, "已存在主机,不可重复添加")
return
elif resp.get("code") != 0:
self.finish_json(1003, "修改主机异常")
return
acc_id = plugin.query("acc", ["id"], {"host_id": host_id, "username": username})
if not acc_id:
self.finish_json(1011, "未发现该服务器信息")
return
acc_id = acc_id[0].get("id", 0)
url = "http://127.0.0.1:7190/asset/update-account"
args = {"args": json.dumps({"host_id": host_id, "acc_id": acc_id,
"param": {"host_ip": ip, "router_ip": "", "router_port": 0,
"protocol": 1, "port": 3389, "auth_type": 1, "username": username,
"password": password, "pri_key": "", "username_prompt": "",
"password_prompt": ""}}).encode()}
# {"code": 0, "message": "", "data": 5}
# 带信息带先插入
resp = yield self.request_api(url, args)
if resp.get("code") != 0:
self.finish_json(1004, "添加服务器账户异常")
return
acc_id = resp.get("data")
args = {"os_type": os_type, "ip": ip, "username": username, "password": "", "name": name, "remark": desc,
"id": host_id, "assets_num": "", "status": status}
# 调用更新接口
err = plugin.update_host(self, args)
# 已经存在数据库
self.finish_json(0, "成功")
class GetHostListHandler(TPBasePluginHandler):
def post(self):
async def post(self):
props = self.get_payload()
args = self.get_payload()
log.i(props)
os_type = props.pop("os_type", 0)
ip = props.pop("ip", "")
search = props.pop("search", "")
status = props.pop("status", 0)
app_id = props.pop("app_id", 0)
sql_filter = {}
sql_order = dict()
sql_order['name'] = 'id'
sql_order['asc'] = True
os_type, status, page_index, page_size = self.param_get(props, ['os_type', 'status', 'pageIndex', 'pageSize'],
0)
ip, search = self.param_get(props, ['ip', 'search', ], '')
sql_limit = dict()
sql_limit['page_index'] = 0
sql_limit['per_page'] = 25
sql_restrict = {}
sql_exclude = {}
_limit = args.get('limit', {"page_index": 0, "per_page": 0})
if _limit['page_index'] < 0:
_limit['page_index'] = 0
if _limit['per_page'] < 10:
_limit['per_page'] = 10
if _limit['per_page'] > 100:
_limit['per_page'] = 100
sql_limit.update(_limit)
_order = args.get("order")
if _order is not None:
sql_order['name'] = _order['k']
sql_order['asc'] = _order['v']
sql_limit['page_index'] = page_index - 1 if page_index - 1 > 0 else 0
sql_limit['per_page'] = page_size
err, total_count, page_index, row_data = \
plugin.get_host_list(sql_limit, os_type, ip, search, status)
......@@ -334,22 +327,24 @@ class GetHostListHandler(TPBasePluginHandler):
item['desc'] = item.pop("remark", "")
item['host_id'] = item.pop("id", 0)
# 绑定详情
# todo 使用公用方法
item['bind'] = plugin.get_bind_info(item['host_id'])
self.finish_json(0, data=row_data)
class GetHostInfoHandler(TPBasePluginHandler):
def post(self):
async def post(self):
props = self.get_payload()
host_id = props.pop("host_id", 0)
mch_no = props.pop("mch_no", "")
host_id = props.get("host_id") or 0
mch_no = props.get("mch_no") or ""
err, host_info = plugin.get_account_info(host_id=host_id, mch_no=mch_no)
if err != TPE_OK:
self.write(json_encode({"res": 0, "ec": "1004", "msg": "设备信息获取异常"}))
self.finish()
if mch_no and not host_id:
# 商家平台 通过商户请求
self.finish_json(0, data=[])
else:
self.finish_json("1004", msg="设备信息获取异常")
return
host_info['desc'] = host_info.pop("remark", "")
......@@ -361,23 +356,28 @@ class GetHostInfoHandler(TPBasePluginHandler):
class GetSessionInfoHandler(TPBasePluginHandler):
async def post(self):
props = self.get_payload()
log.i(json.dumps(props))
if not self.check_ip(props):
self.finish_json(1001, "IP不符合规范")
return
host_id = props.pop("host_id", 0)
mch_no = props.pop("mch_no", "")
host_id = props.get("host_id") or 0
mch_no = props.get("mch_no") or ""
ip = props.get("ip") or ""
username = props.get("username") or ""
password = props.get("password") or ""
if not host_id and not mch_no and not (ip and username and password):
self.finish_json(1001, "缺少必要参数异常")
return
ip = props.pop("ip", "")
username = props.pop("username", 0)
password = props.pop("password", 0)
data = {"ip": ip, "os_type": 1, "username": username, "password": password}
url = "http://127.0.0.1:7190/plugin/update_host"
await self.request_api(url, json=data)
if ip and username and password:
data = {"ip": ip, "os_type": 1, "username": username, "password": password}
url = "http://127.0.0.1:7190/plugin/update_host"
resp = await self.request_api(url, json=data)
err, info = plugin.get_session_info(host_id, mch_no, ip)
err, info, host_id = plugin.get_session_info(host_id, mch_no, ip)
url = "http://127.0.0.1:7190/ops/get-session-id"
args = {"args": json.dumps(
......@@ -390,70 +390,135 @@ class GetSessionInfoHandler(TPBasePluginHandler):
if isinstance(resp, dict):
ip = ip or plugin.get_host_ip(host_id)
resp = {"teleport_ip": "172.30.10.104", "teleport_port": 52089, "remote_host_ip": ip,
"session_id": resp.get("session_id"), "protocol_type": 1, "protocol_sub_type": 100,
"protocol_flag": resp.get("protocol_flag"), "rdp_width": 0, "rdp_height": 0, "rdp_console": False}
"session_id": resp.get("data", {}).get("session_id"), "protocol_type": 1, "protocol_sub_type": 100,
"protocol_flag": resp.get("data", {}).get("protocol_flag"), "rdp_width": 0, "rdp_height": 0,
"rdp_console": False}
resp = """http://localhost:50022/api/run/{}""".format(json.dumps(resp))
self.finish_json(0, data=[resp])
return
class BindPayAccountHandler(TPBasePluginHandler):
async def add_members(self, biz_id, host_id):
args = {"args": json.dumps(
{"id": -1, "role": 2, "auth_type": 0, "username": str(biz_id), "surname": "", "email": "", "mobile": "",
"qq": "", "wechat": "", "desc": ""}).encode()}
url = 'http://127.0.0.1:7190/user/update-user'
# biz 创建对象
resp = await self.request_api(url, args)
user_id = resp.get("data", 0) or self.query("user", "id", {"username": str(biz_id)})
url = "http://172.30.10.104:7190/ops/policy/update"
args = {"args": json.dumps({"id": -1, "name": str(biz_id), "desc": ""})}
# 创建权限组
resp = await self.request_api(url, args)
policy_id = resp.get("data", 0) or self.query("ops_policy", "id", {"name": str(biz_id)})
# 运维权限
url = "http://172.30.10.104:7190/ops/policy/add-members"
args = {"args": json.dumps(
{"policy_id": policy_id, "type": 0, "rtype": 1, "members": [{"id": user_id, "name": str(biz_id)}]})}
resp = await self.request_api(url, args)
ip = self.query("host", 'ip', {"id": host_id})
url = "http://172.30.10.104:7190/ops/policy/add-members"
args = {"args": json.dumps(
{"policy_id": policy_id, "type": 1, "rtype": 5, "members": [{"id": host_id, "name": ip}]})}
resp = await self.request_api(url, args)
def allot_ip(self, host_assigned, ip, username, password):
return
def update(self, id):
pass
async def post(self):
props = self.get_payload()
args = props
if not self.check_ip(props):
self.finish_json(1001, "IP不符合规范")
return
biz_id = props.get("biz_id", 0)
host_assigned = props.get("host_assigned") or 0
host_id = props.get("host_id", 0)
comp_id, biz_id, host_assigned, host_id = \
self.param_get(props, ['comp_id', 'biz_id', 'host_assigned', 'host_id'], 0)
host_assigned = int(host_assigned)
ip, username, host_password, account, password, mch_no \
= self.param_get(props, ['ip', 'username', 'host_password', 'account', 'password', 'mch_no'], "")
if not biz_id:
self.finish_json(1001, "缺少必要参数异常:biz_id")
if not biz_id or not mch_no or not comp_id or not account or not password:
self.finish_json(1001, "缺少必要参数异常:biz_id,mch_no")
return
if host_assigned == 1:
# 自动分配功能
err, info = free_host()
if err == TPE_OK:
args['host_id'] = info
# not host_id and not host_assigned and (not ip or not username or not host_password)
if not host_id and not host_assigned and (not ip or not username or not host_password):
self.finish_json(1001, "手动分配,缺少必要参数异常:ip,username,password")
return
if not host_id:
if int(host_assigned) == 1:
# 自动分配功能
err, info = free_host()
if err == TPE_OK:
host_id = info
else:
self.finish_json(1010, "未发现空闲主机")
return
else:
self.finish_json(1010, "未发现空闲主机")
return
data = {"ip": ip, "os_type": 1, "username": username, "password": host_password}
url = "http://127.0.0.1:7190/plugin/update_host"
resp = await self.request_api(url, json=data)
host_id = resp.get("data", 0) or self.query("host", 'id', {"ip": ip})
args = {"args": json.dumps(
{"id": -1, "role": 2, "auth_type": 0, "username": str(biz_id), "surname": "", "email": "", "mobile": "",
"qq": "", "wechat": "", "desc": ""}).encode()}
if not host_id:
self.finish_json(1010, "无法找到对应主机信息")
return
url = 'http://127.0.0.1:7190/user/update-user'
# biz 创建对象
resp = await self.request_api(url, args)
# {'code': 0, 'message': '', 'data': []}
# {'code': 8, 'message': '', 'data': []} 已存在
url = "http://172.30.10.104:7190/ops/policy/update"
args = {"args": json.dumps({"id": -1, "name": str(biz_id), "desc": ""})}
# 创建权限组
resp = await self.request_api(url, args)
# {'code': 0, 'message': '', 'data': []}
# {'code': 8, 'message': '', 'data': 0} 已存在
# 查询设备并自动赋权
# url = "http://172.30.10.104:7190/ops/policy/add-members"
# args = {"args": json.dumps({"policy_id": 1, "type": 0, "rtype": 1, "members": [{"id": 3, "name": "123456"}]})}
# resp = await self.request_api(url, args)
# args = {"args": json.dumps(
# {"policy_id": 1, "type": 1, "rtype": 5, "members": [{"id": 21, "name": "119.28.116.176"}]})}
# resp = await self.request_api(url, args)
args = props
args['username'] = args.get("account") or ""
args['host_assigned'] = args.get("host_assigned") or 0
args['host_id'] = host_id
id = self.query("remote_account_host_bind", "id", {"host_id": host_id, "mch_no": mch_no})
password = des_encrypt(password)
# xiugai
if id:
args = {"mch_no": mch_no, "comp_id": comp_id, "host_id": host_id, "host_assigned": host_assigned,
"account_source": 1, "account": account, "password": password, "login_status": 0, "mch_name": ""}
err = plugin.update_account_host_bind(self, args)
if err == TPE_FAILED:
self.finish_json(1011, "不允许修改公司资质")
elif err == TPE_NOT_EXISTS:
self.finish_json(1012, "设备不存在")
elif err == TPE_OK:
self.finish_json(0)
return
args['password'] = password
err, info = plugin.add_account_host_bind(self, args)
self.finish_json(0)
if err == TPE_EXISTS:
self.finish_json(1011, "绑定的支付宝账户已存在")
elif err == TPE_FAILED:
self.finish_json(1011, "不可跨资质绑定")
elif err == TPE_NOT_EXISTS:
self.finish_json(1011, "绑定设备不存在")
else:
self.finish_json(0)
def put(self):
if err != TPE_OK:
return
await self.add_members(biz_id, host_id)
async def put(self):
props = self.get_payload()
args = props
......@@ -461,31 +526,79 @@ class BindPayAccountHandler(TPBasePluginHandler):
self.finish_json(1001, "IP不符合规范")
return
args['username'] = args.get("account") or ''
args['host_assigned'] = args.get("host_assigned") or 0
comp_id, biz_id, host_assigned, host_id = \
self.param_get(props, ['comp_id', 'biz_id', 'host_assigned', 'host_id'], 0)
ip, username, host_password, account, password, mch_no \
= self.param_get(props, ['ip', 'username', 'host_password', 'account', 'password', 'mch_no'], "")
host_id = host_id or self.query('remote_account_host_bind', 'host_id', {"mch_no": mch_no})
if not host_id:
self.finish_json(1010, "未发现对应主机信息")
return
args = {"mch_no": mch_no, "comp_id": comp_id, "host_id": host_id, "host_assigned": host_assigned,
"account_source": 1, "account": account, "password": password, "login_status": 0, "mch_name": ""}
err = plugin.update_account_host_bind(self, args)
if err == TPE_FAILED:
self.finish_json(1011, "不允许修改公司资质")
return
elif err == TPE_NOT_EXISTS:
self.finish_json(1012, "设备不存在")
elif err == TPE_OK:
self.finish_json(0)
if err != TPE_OK:
return
class AccountStatusHandler(TPBasePluginHandler):
def post(self):
async def post(self):
prop = self.get_payload()
mch_name = prop.get("mch_name", "")
login_status = prop.get("login_status", "")
ip = self.request.remote_ip
mch_no = prop.get("mch_no") or ""
mch_name = prop.get("mch_name") or ""
login_status = prop.get("login_status") or 0
host_id = self.query("host", ["id"], {"ip": ip})
if not host_id:
self.finish_json(1011, "未发现该服务器信息")
return
plugin.update("tp_remote_account_host_bind", {"mch_name": mch_name, "login_status": login_status},
{"host_id": host_id, "mch_no": mch_no})
self.finish_json(0)
class AccountInfoHandler(TPBasePluginHandler):
def post(self):
def key(self, timestamp):
key = '{}{}'.format(KEY, timestamp)
return
async def post(self):
prop = self.get_payload()
info = prop.get("info")
info = prop.get("info") or ""
timestamp = prop.get("timestamp")
if not timestamp:
self.finish_json(1001, "传递参数错误")
return
accounts = plugin.query('remote_account_host_bind', ['username', 'password'],
'account_source=0 and ip={}'.format(info))
accounts = {item[0]: item[1] for item in accounts}
self.finish_json(0, data=[accounts])
# md5 (key + timestamp)[:8]
key = md5('{}{}'.format(KEY, timestamp))[:8]
info = des_descrypt(info, key)
info = info.decode()
# ip = en
if info:
host_id = self.query('host', 'id', {"ip": info})
accounts = plugin.query('remote_account_host_bind', ['account', 'password'],
{"account_source": 1, "host_id": host_id})
info = {k: v for account in accounts for k, v in account.items()}
timestamp = int(time.time())
key = md5('{}{}'.format(KEY, timestamp))[:8]
info = json.dumps(info)
data = des_encrypt(info, key).decode()
self.finish_json(0, data=[{"info": data, "timestamp": timestamp}])
else:
self.finish_json(1001, "传递参数错误")
......@@ -184,19 +184,25 @@ def add_account_host_bind(handler, args):
operator = handler.get_current_user()
# 1. 判断账户是否已经存在了
sql = 'SELECT id FROM tp_remote_account_host_bind WHERE account="{}"'.format(args['account'])
sql = 'SELECT id FROM tp_remote_account_host_bind WHERE account="{}" '.format(args['account'])
db_ret = db.query(sql)
if db_ret is not None and len(db_ret) > 0:
return TPE_EXISTS, 0
# 2. 判断host_id 是否存在
# todo 只允许同资质绑定
sql = 'SELECT id FROM tp_remote_host WHERE id="{}"'.format(args['host_id'])
db_ret = db.query(sql)
if not db_ret:
return TPE_NOT_EXISTS, 0
sql = 'INSERT INTO `tp_remote_account_host_bind` (biz_id,mch_no, comp_id, host_id, host_assigned, account_source, username, password, login_status, mch_name, create_tiem, create_by, update_time, update_by) VALUES ' \
# 3. 是否已经存在不同资质公司
sql = 'SELECT comp_id FROM tp_remote_account_host_bind WHERE host_id={}'.format(args['host_id'])
db_ret = db.query(sql)
comp_id = args.get('comp_id')
if db_ret and (comp_id,) not in db_ret:
return TPE_FAILED, 0
sql = 'INSERT INTO `tp_remote_account_host_bind` (biz_id,mch_no, comp_id, host_id, host_assigned, account_source, account, password, login_status, mch_name, create_tiem, create_by, update_time, update_by) VALUES ' \
'({biz_id},"{mch_no}", {comp_id}, {host_id}, {host_assigned}, {account_source}, "{account}", "{password}", {login_status},"{mch_name}", "{create_time}", "{create_by}", "{update_time}", "{update_by}");' \
''.format(mch_no=args.get("mch_no", ""), comp_id=args.get("comp_id", 0), host_id=args.get("host_id", 0),
host_assigned=args.get("host_assigned", 0), account_source=args.get("account_source", 1),
......@@ -229,6 +235,9 @@ def update_account_host_bind(handler, args):
sql = 'SELECT comp_id FROM tp_remote_account_host_bind WHERE host_id="{}"'.format(args['host_id'])
db_ret = db.query(sql)
if not db_ret:
return TPE_NOT_EXISTS
# 不允许修改公司资质
if db_ret[0][0] != args['comp_id']:
return TPE_FAILED
......@@ -243,11 +252,11 @@ def update_account_host_bind(handler, args):
id = db_ret[0][0]
sql = 'UPDATE `tp_remote_account_host_bind` SET ' \
'`mch_no`="{mch_no}", `comp_id`={comp_id}, `host_id`="{host_id}", ' \
'`host_assigned`={host_assigned}, `account_source`="{account_source}", `username`="{username}", `password`="{password}", ' \
'`host_assigned`={host_assigned}, `account_source`="{account_source}", `account`="{account}", `password`="{password}", ' \
'`login_status`="{login_status}", `mch_name`="{mch_name}", `update_time`="{update_time}", `update_by`="{update_by}" WHERE `id`={id};' \
.format(mch_no=args.get("mch_no", ""), comp_id=args.get("comp_id", 0), host_id=args.get("host_id", 0),
host_assigned=args.get("host_assigned", 0), account_source=args.get("account_source", 1),
username=args.get("username", ""), password=args.get("password", ""),
account=args.get("account", ""), password=args.get("password", ""),
login_status=args.get("login_status", 0), mch_name=args.get("mch_name", ""),
update_time=_time_now, update_by=operator['id'], id=id)
......@@ -268,10 +277,10 @@ def get_session_info(host_id, mch_no, ip):
if host_id:
sql = 'SELECT username FROM tp_remote_host WHERE id="{}"'.format(host_id)
elif ip:
sql = """select a.username
sql = """select a.username,a.id
from tp_remote_host a where ip = "{}" """.format(ip)
elif mch_no:
sql = """select a.username
sql = """select a.username,a.id
from tp_remote_host a left join tp_remote_account_host_bind b on a.id = b.host_id
where b.mch_no = "" """.format(mch_no)
else:
......@@ -280,11 +289,12 @@ def get_session_info(host_id, mch_no, ip):
db_ret = db.query(sql)
username = db_ret[0][0]
host_id = host_id or db_ret[0][1]
sql = 'SELECT id FROM tp_acc WHERE host_id="{}" and username = "{}"'.format(host_id, username)
db_ret = db.query(sql)
acc_id = db_ret[0][0]
return TPE_OK, acc_id
return TPE_OK, acc_id, host_id
def get_host_ip(host_id):
......@@ -295,15 +305,56 @@ def get_host_ip(host_id):
return ip
def query(table: str, fields: list, where: str = None):
def query(table: str, fields: list, where: dict):
s = SQL(get_db())
s.select_from(table, fields, alt_name='a')
if where:
s.where('a.{}'.format(where))
_where = ' and '.join(
['`{key}`={value}'.format(key=k, value='"{}"'.format(v) if isinstance(v, str) else v) for k, v in
where.items()])
s.where(_where)
err = s.query()
if err != TPE_OK:
return None
return {}
return s.recorder
def query_one(table: str, fields: list, where: dict):
s = SQL(get_db())
s.select_from(table, fields, alt_name='a')
if where:
_where = ' and '.join(
['`{key}`={value}'.format(key=k, value='"{}"'.format(v) if isinstance(v, str) else v) for k, v in
where.items()])
s.where(_where)
err = s.query()
if err != TPE_OK:
return {}
if s.recorder.__len__() > 0:
return s.recorder[0]
else:
return {}
def update(table: str, fields: dict, where: dict):
db = get_db()
_set = ','.join(['`{key}`={value}'.format(key=k, value='"{}"'.format(v) if isinstance(v, str) else v) for k, v in
fields.items()])
_where = ' and '.join(
['`{key}`={value}'.format(key=k, value='"{}"'.format(v) if isinstance(v, str) else v) for k, v in
where.items()])
sql = 'UPDATE `{table}` SET {set} WHERE {where};'.format(table=table, set=_set, where=_where)
print(sql)
db_ret = db.exec(sql)
if not db_ret:
return TPE_DATABASE
return TPE_OK
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment