Commit b4c13ad8 authored by BH's avatar BH

添加入参解析方法

parent 3071123f
......@@ -313,7 +313,7 @@ class AppConfig(BaseAppConfig):
self.set_default('database::mysql-password', 'password', 'mysql-password=password')
self.set_default('plugin::core_host', '127.0.0.1', 'core_host=127.0.0.1')
self.set_default('plugin::consul', '127.0.0.1', 'consul=http://172.30.10.128:6010')
self.set_default('plugin::consul', '127.0.0.1', 'consul=http://172.30.20.128:6010')
self.set_default('plugin::release_ip', '127.0.0.1', 'release_ip=127.0.0.1')
self.set_default('plugin::server', '127.0.0.1', 'server=127.0.0.1')
self.set_default('plugin::manager_host', 'http://121.196.33.88:5566', 'manager_host=http://121.196.33.88:5566')
......
......@@ -308,6 +308,7 @@ controllers = [
# websocket for real-time information
(r'/plugin/exe_download_url', plugin.ExeDownloadHandler),
# ws-client call 'http://ip:7190/ws/action/'
(r'/ws/(.*)', ws.WebSocketHandler),
(r'/.*', index.CatchAllHandler),
]
......
......@@ -52,7 +52,12 @@ def login(path, username, password, host):
def add_site(site, host):
# 添加站點
"""
添加站点
:param site: 站点名称
:param host: 站点地址
:return:
"""
url = "http://{}/site?action=AddSite".format(host)
user = 'sql{}'.format(site.replace(".", "_"))
webname = json.dumps({"domain": site, "domainlist": [], "count": 1})
......@@ -70,6 +75,12 @@ def add_site(site, host):
def del_site(ip, site):
"""
删除站点
:param ip:
:param site:
:return:
"""
url = "http://{}/data?action=getData".format(ip)
data = {"tojs": "site.get_list", "table": "sites", "limit": 15, "p": 1, "search": "", "order": "id desc",
"type": -1}
......@@ -85,28 +96,32 @@ def del_site(ip, site):
def install_dbshop(site, host):
"""
安装 dbshop 商城
:param site:
:param host:
:return:
"""
url = "http://{}/deployment?action=GetList".format(host)
data = {"type": 0}
session.post(url, data)
# 一键部署接口
url = "http://{}/deployment?action=SetupPackage".format(host)
data = {"dname": "DBShop", "site_name": site, "php_version": "56"}
i = 0
while True:
for i in range(3):
resp = session.post(url, data=data)
if resp.status_code == 200:
break
i += 1
if i > 3:
break
time.sleep(10)
# {"status": true, "msg": {"db_config": "", "run_path": "/", "php_versions": "54,55,56,70,71,72,73", "admin_username": "", "success_url": "/install", "chmod": [], "remove_file": [], "php_ext": ["fileinfo"], "admin_password": ""}}
# http://121.196.33.88:8888/deployment?action=GetSpeed
# {"pre": 0, "total": 0, "speed": 0, "name": "\u5b89\u88c5\u5fc5\u8981\u7684PHP\u6269\u5c55", "used": 0}
pre = 1
while pre != 0:
# 初次调用,下载文件包
for i in range(20):
url = "http://{}/deployment?action=GetSpeed".format(host)
resp = session.get(url)
pre = resp.json().get("pre", 1)
......@@ -119,6 +134,11 @@ def install_dbshop(site, host):
def mysql_root_pwd(ip):
"""
mysql root 密码获取
:param ip:
:return:
"""
url = "http://{}/data?action=getKey".format(ip)
data = {"table": "config", "key": "mysql_root", "id": "1"}
resp = session.post(url, data)
......@@ -128,7 +148,13 @@ def mysql_root_pwd(ip):
def shop_config(host, site, webname="DBShop电子商务系统"):
pwd = mysql_root_pwd(host)
"""
商城初始化相关接口
:param host:
:param site:
:param webname:
:return:
"""
host = host.replace(":8888", "")
# 等待时间让网页进行加载
time.sleep(10)
......@@ -144,16 +170,11 @@ def shop_config(host, site, webname="DBShop电子商务系统"):
resp = session.post(url, data)
i = 0
while True:
for i in range(5):
resp = session.post(url, data=data)
print("check db", url, data, resp.content)
if resp.text != "false":
break
i += 1
if i > 5:
break
time.sleep(10)
if resp.text == "false":
......@@ -175,6 +196,11 @@ def shop_config(host, site, webname="DBShop电子商务系统"):
def check_shop(site):
"""
确认商城安装情况
:param site:
:return:
"""
url = "http://{}".format(site)
try:
resp = requests.get(url)
......@@ -195,6 +221,11 @@ def get_domain(ip, id):
def check_all_domain(ip):
"""
检查宝塔下所有的站点
:param ip:
:return:
"""
url = "http://{}/data?action=getData".format(ip)
# tojs=site.get_list&table=sites&limit=15&p=1&search=&order=id desc&type=-1
data = {"tojs": "site.get_list", "table": "sites", "limit": 15, "p": 1, "search": "", "order": "id desc",
......@@ -219,6 +250,11 @@ def check_all_domain(ip):
def sub_domain(site):
"""
子域名处理
:param site:
:return:
"""
if site.count('.') == 1:
pay_site = 'pay.' + site
else:
......@@ -377,6 +413,14 @@ def install_shop(ip, site, webname):
def add_site_domain(id, ip, site, webname):
"""
将域名添加至站点
:param id:
:param ip:
:param site:
:param webname:
:return:
"""
url = "http://{}/data?action=getData".format(ip)
data = {"table": "domain", "list": True, "search": id}
resp = session.post(url, data)
......@@ -389,6 +433,13 @@ def add_site_domain(id, ip, site, webname):
def add_nginx(ip, id, site):
"""
修改 nginx 配置
:param ip:
:param id:
:param site:
:return:
"""
sites = get_domain(ip, id)
url = "http://{}/files?action=GetFileBody".format(ip)
......@@ -410,7 +461,12 @@ def add_nginx(ip, id, site):
def check_ssl(ip, sub_domain):
# 获取已部署证书
"""
获取已部署证书
:param ip:
:param sub_domain:
:return:
"""
url = "http://{}/ssl?action=GetCertList".format(ip)
resp = session.post(url)
......@@ -421,7 +477,13 @@ def check_ssl(ip, sub_domain):
def set_old_ssl(ip, site, cert_name):
# 部署已存在证书
"""
已存在域名证书,直接使用
:param ip:
:param site:
:param cert_name:
:return:
"""
url = "http://{}/ssl?action=SetCertToSite".format(ip)
data = {"certName": cert_name, "siteName": site}
resp = session.post(url, data)
......@@ -449,7 +511,14 @@ def start_https(ip, site):
def set_ssl(ip, site, id, sub_domain):
# 已部署证书的不再部署
"""
部署 https 证书
:param ip:
:param site:
:param id:
:param sub_domain:
:return:
"""
if ssl_status(ip, site):
return
......@@ -496,14 +565,9 @@ def run(ip, path, user, pwd, site, webname, sub_domain=""):
print(login(path, user, pwd, ip))
print("完成宝塔登录配置")
# if check_shop(site):
# print("商城已存在")
# return
shop_id, name = check_all_domain(ip)
if shop_id:
print("商城已存在", shop_id, "name", name)
add_site_domain(shop_id, ip, ip.replace(":8888", ""), name)
add_site_domain(shop_id, ip, site, name)
if sub_domain:
add_site_domain(shop_id, ip, sub_domain, name)
......@@ -545,7 +609,3 @@ def main():
if __name__ == '__main__':
main()
# run("34.92.159.68:8888", path='9f57b254', pwd='950bc7da', site='pay.xamsmsm.com', user='ppvtidah',
# webname='测试', sub_domain="pay.xamsmsm.com")
# print(login(path, user, pwd, ip))
# set_ssl(ip, "34.92.159.68", 5, "pay.xamsmsm.com")
......@@ -26,6 +26,8 @@ from app.base.configs import tp_cfg
from pyDes import des, CBC, PAD_PKCS5
import math
from controller import reqparse
def current_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
......@@ -127,6 +129,7 @@ class TPBasePluginHandler(TPBaseHandler):
cfg = tp_cfg()
release_ip = cfg.plugin.release_ip
self.release_ip = release_ip
self.parse = None
async def prepare(self):
# req = requests.get("http://txt.go.sohu.com/ip/soip")
......@@ -207,6 +210,9 @@ class TPBasePluginHandler(TPBaseHandler):
def query(self, table, field, filter):
return plugin.query_one(table, [field], filter).get(field, 0)
def req_parse(self, required: tuple = ()):
pass
class UpdateHostHandler(TPBasePluginHandler):
def generate_assets_num(self, ip, os_type):
......@@ -219,30 +225,27 @@ class UpdateHostHandler(TPBasePluginHandler):
assets_num = 'L' + assets_num
return assets_num
def req_parse(self, required: tuple = ()):
self.parse = reqparse.RequestParser()
self.parse.add_argument("os_type", type=int, help='系统类型', required='host_id' in required, choices=[1, 2])
self.parse.add_argument("host_id", type=int, required='host_id' in required, default=0)
self.parse.add_argument("status", type=int, help='商城域名', default=0)
self.parse.add_argument("ip", type=str, help='远程服务器IP', required='ip' in required, trim=True)
self.parse.add_argument("username", type=str, help='服务器用户名', required='username' in required, trim=True)
self.parse.add_argument("password", type=str, help='服务器密码', required='password' in required, trim=True)
self.parse.add_argument("name", type=str, help='服务器命名', trim=True)
self.parse.add_argument("desc", type=str, help='服务器IP', trim=True)
args = self.parse.parse_args(req=self.get_payload())
# todo 检查ip
# if not self.check_ip(props):
# self.finish_json(1001, "IP不符合规范")
# return
return args
@tornado.gen.coroutine
def post(self):
props = self.get_payload()
if not self.check_ip(props):
self.finish_json(1001, "IP不符合规范")
return
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', ], '')
password = password.replace("*", "")
try:
os_type = int(os_type)
host_id = int(host_id)
# app_id = int(app_id)
status = int(status)
except:
self.finish_json(1001, "参数传递异常,请检查请求参数")
return
# “res”:1,“ec”:”0”,“msg”:”成功”
if not os_type or not ip or not username or not password:
self.finish_json(1001, "缺少必要参数异常")
return
args = self.req_parse(('os_type', 'ip', 'username', 'password'))
ip, os_type, name, desc, username, password, status = args.ip, args.os_type, args.name, args.desc, args.username, args.password, args.status
assets_num = self.generate_assets_num(ip, os_type)
......@@ -266,19 +269,11 @@ class UpdateHostHandler(TPBasePluginHandler):
host_id = resp.get("data")
url = "http://127.0.0.1:7190/asset/update-account"
if os_type == 1:
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()}
else:
args = {"args": json.dumps({"host_id": host_id, "acc_id": -1,
"param": {"host_ip": ip, "router_ip": "", "router_port": 0,
"protocol": 2, "port": 22, "auth_type": 1, "username": username,
"password": password, "pri_key": "", "username_prompt": "",
"password_prompt": ""}}).encode()}
args = {"args": json.dumps({"host_id": host_id, "acc_id": -1,
"param": {"host_ip": ip, "router_ip": "", "router_port": 0,
"protocol": os_type, "port": 3389 if os_type == 1 else 22, "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)
......@@ -302,32 +297,9 @@ class UpdateHostHandler(TPBasePluginHandler):
@tornado.gen.coroutine
def put(self):
props = self.get_payload()
if not self.check_ip(props):
self.finish_json(1001, "IP不符合规范")
return
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', ], '')
password = password.replace("*", "")
try:
os_type = int(os_type)
host_id = int(host_id)
status = int(status)
except:
self.finish_json(1001, "参数传递异常,请检查请求参数")
return
# “res”:1,“ec”:”0”,“msg”:”成功”
if not os_type or not ip or not username or not host_id:
self.finish_json(1001, "缺少必要参数异常")
return
old_ip = self.query('remote_host', 'ip', {"id": host_id})
if old_ip != ip:
self.finish_json(1001, "主机IP不可修改")
return
# 增加 host_id
args = self.req_parse(('host_id',))
ip, os_type, name, desc, username, password, status, host_id = args.ip, args.os_type, args.name, args.desc, args.username, args.password, args.status, args.host_id
assets_num = self.generate_assets_num(ip, os_type)
......@@ -352,19 +324,12 @@ class UpdateHostHandler(TPBasePluginHandler):
return
url = "http://127.0.0.1:7190/asset/update-account"
if os_type == 1:
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()}
else:
args = {"args": json.dumps({"host_id": host_id, "acc_id": acc_id,
"param": {"host_ip": ip, "router_ip": "", "router_port": 0,
"protocol": 2, "port": 22, "auth_type": 1, "username": username,
"password": password, "pri_key": "", "username_prompt": "",
"password_prompt": ""}}).encode()}
args = {"args": json.dumps({"host_id": host_id, "acc_id": acc_id,
"param": {"host_ip": ip, "router_ip": "", "router_port": 0,
"protocol": os_type, "port": 3389 if os_type == 1 else 22,
"auth_type": 1, "username": username,
"password": password, "pri_key": "", "username_prompt": "",
"password_prompt": ""}}).encode()}
# {"code": 0, "message": "", "data": 5}
# 带信息带先插入
......@@ -393,25 +358,20 @@ class UpdateHostHandler(TPBasePluginHandler):
class GetHostListHandler(TPBasePluginHandler):
async def post(self):
props = self.get_payload()
os_type, status, page_index, page_size = self.param_get(props, ['os_type', 'status', 'pageIndex', 'pageSize'],
0)
ip, name = self.param_get(props, ['ip', 'name', ], '')
def req_parse(self, required: tuple = ()):
self.parse = reqparse.RequestParser()
self.parse.add_argument("os_type", type=int, help='', )
self.parse.add_argument("status", type=int, help='', default=0)
self.parse.add_argument("pageIndex", type=int, help='', required=True, )
self.parse.add_argument("pageSize", type=int, help='', required=True, )
self.parse.add_argument("ip", type=str, help='', trim=True)
self.parse.add_argument("name", type=str, help='', trim=True)
args = self.parse.parse_args(req=self.get_payload())
return args
try:
os_type = int(os_type)
status = int(status)
page_index = int(page_index)
page_size = int(page_size)
except:
self.finish_json(1001, "参数传递异常,请检查请求参数")
return
if not page_index or not page_size:
self.finish_json(1001, "缺少必要参数异常")
return
async def post(self):
args = self.req_parse()
page_index, page_size, os_type, ip, name, status = args.page_index, args.page_size, args.os_type, args.ip, args.name, args.status
sql_limit = dict()
sql_limit['page_index'] = page_index - 1 if page_index - 1 > 0 else 0
......@@ -446,17 +406,17 @@ class GetHostListHandler(TPBasePluginHandler):
class GetHostInfoHandler(TPBasePluginHandler):
def req_parse(self, required: tuple = ()):
self.parse = reqparse.RequestParser()
self.parse.add_argument("host_id", type=int, help='', )
self.parse.add_argument("mch_no", type=int, help='', default=0)
args = self.parse.parse_args(req=self.get_payload())
return args
async def post(self):
try:
props = self.get_payload()
host_id = props.get("host_id") or 0
mch_no = props.get("mch_no") or ""
try:
host_id = int(host_id)
except:
self.finish_json(1001, "提交参数异常,请检查请求参数")
return
args = self.req_parse()
host_id, mch_no = args.host_id, args.mch_no
err, host_info = plugin.get_account_info(host_id=host_id, mch_no=mch_no)
if err != TPE_OK:
......@@ -478,26 +438,27 @@ class GetHostInfoHandler(TPBasePluginHandler):
class GetSessionInfoHandler(TPBasePluginHandler):
async def post(self):
props = self.get_payload()
def req_parse(self, required: tuple = ()):
self.parse = reqparse.RequestParser()
# 三选一
self.parse.add_argument("host_id", type=int, help='', )
if not self.check_ip(props):
self.finish_json(1001, "IP不符合规范")
return
self.parse.add_argument("mch_no", type=int, help='', default=0)
host_id = props.get("host_id") or 0
mch_no = props.get("mch_no") or ""
self.parse.add_argument("ip", type=str, help='', )
self.parse.add_argument("username", type=str, help='', )
self.parse.add_argument("password", type=str, help='', trim=True)
ip = props.get("ip") or ""
username = props.get("username") or ""
password = props.get("password") or ""
try:
host_id = int(host_id)
except:
self.finish_json(1001, "提交参数异常,请检查请求参数")
return
args = self.parse.parse_args(req=self.get_payload())
# todo
# if not self.check_ip(props):
# self.finish_json(1001, "IP不符合规范")
# return
return args
async def post(self):
args = self.req_parse()
host_id, mch_no, ip, username, password = args.host_id, args.mch_no, args.ip, args.username, args.password
if not host_id and not mch_no and not (ip and username and password):
self.finish_json(1001, "缺少必填项")
return
......@@ -591,41 +552,32 @@ class BindPayAccountHandler(TPBasePluginHandler):
{"policy_id": policy_id, "type": 1, "rtype": 5, "members": [{"id": host_id, "name": ip}]}).encode()}
resp = await self.request_api(url, args)
def allot_ip(self, host_assigned, ip, username, password):
return
def update(self, id):
pass
def req_parse(self, required: tuple = ()):
self.parse = reqparse.RequestParser()
self.parse.add_argument("comp_id", type=int, required=True, help='', )
self.parse.add_argument("biz_id", type=int, help='', required=True, default=1)
self.parse.add_argument("host_assigned", type=int, help='', )
self.parse.add_argument("host_id", type=int, help='', )
self.parse.add_argument("ip", type=str, help='', )
self.parse.add_argument("username", type=str, help='', )
self.parse.add_argument("host_password", type=str, help='', )
self.parse.add_argument("account", type=str, help='', )
self.parse.add_argument("password", type=str, help='', )
self.parse.add_argument("mch_no", type=str, help='', )
args = self.parse.parse_args(req=self.get_payload())
# todo
# if not self.check_ip(props):
# self.finish_json(1001, "IP不符合规范")
# return
return args
async def post(self):
props = self.get_payload()
if not self.check_ip(props):
self.finish_json(1001, "IP不符合规范")
return
comp_id, biz_id, host_assigned, host_id = \
self.param_get(props, ['comp_id', 'biz_id', 'host_assigned', 'host_id'], 0)
biz_id = biz_id or 1
try:
host_assigned = int(host_assigned)
host_id = int(host_id)
comp_id = int(comp_id)
biz_id = int(biz_id)
except:
self.finish_json(1001, "提交参数异常,请检查请求参数")
return
ip, username, host_password, account, password, mch_no \
= self.param_get(props, ['ip', 'username', 'host_password', 'account', 'password', 'mch_no'], "")
# password = password.replace("*", "")
args = self.req_parse()
mch_no, ip, host_id, account, password, username, host_password, host_assigned, comp_id, biz_id = args.mch_no, args.ip, args.host_id, args.account, args.password, args.username, args.host_password, args.host_assigned, args.comp_id, args.biz_id
host_password = host_password.replace("*", "")
if not biz_id or not mch_no or not comp_id:
self.finish_json(1001, "缺少必填项")
return
if host_id and not account:
self.finish_json(1001, "缺少必填项")
return
......@@ -668,9 +620,6 @@ class BindPayAccountHandler(TPBasePluginHandler):
status = self.query("remote_host", "status", {"id": host_id})
args = props
args['host_id'] = host_id
id = self.query("remote_account_host_bind", "id", {"host_id": host_id, "mch_no": mch_no})
des_password = des_encrypt(password).decode()
......@@ -726,47 +675,22 @@ class BindPayAccountHandler(TPBasePluginHandler):
await self.add_members(biz_id, host_id)
async def put(self):
props = self.get_payload()
args = props
if not self.check_ip(props):
self.finish_json(1001, "IP不符合规范")
return
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'], "")
password = password.replace("*", "")
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, "不允许修改公司资质")
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 req_parse(self, required: tuple = ()):
self.parse = reqparse.RequestParser()
self.parse.add_argument("mch_no", type=int, help='', )
self.parse.add_argument("mch_name", type=str, help='', )
self.parse.add_argument("login_status", type=int, help='', )
args = self.parse.parse_args(req=self.get_payload())
return args
class AccountStatusHandler(TPBasePluginHandler):
async def post(self):
prop = self.get_payload()
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
args = self.req_parse()
mch_no, mch_name, login_status = args.mch_no, args.mch_name, args.login_status
host_id = self.query("host", ["id"], {"ip": ip})
......@@ -781,15 +705,17 @@ class AccountStatusHandler(TPBasePluginHandler):
class AccountInfoHandler(TPBasePluginHandler):
async def post(self):
prop = self.get_payload()
info = prop.get("info") or ""
info1 = prop.get("info1") or ""
timestamp = prop.get("timestamp")
def req_parse(self, required: tuple = ()):
self.parse = reqparse.RequestParser()
self.parse.add_argument("info", type=str, required=True, help='', )
self.parse.add_argument("info1", type=str, help='', required=True, default=1)
self.parse.add_argument("timestamp", type=int, help='', )
args = self.parse.parse_args(req=self.get_payload())
return args
if not timestamp:
self.finish_json(1001, "传递参数错误")
return
async def post(self):
args = self.req_parse()
info, info1, timestamp = args.info, args.info1, args.timestamp
# md5 (key + timestamp)[:8]
key = md5('{}{}'.format(KEY, timestamp))[:8]
......@@ -836,82 +762,36 @@ class ShopInfoHandler(TPBasePluginHandler):
info = traceback.format_exc()
log.e("设备详情,异常信息:{}".format(info))
async def put(self):
try:
#
props = self.get_payload()
domain = props.get("domain") or ""
name = props.get("name") or ""
host_id = props.get("host_id") or 0
url = props.get("url") or ""
status = props.get("status") or 0
username = props.get("username") or ""
password = props.get("password") or ""
remark = props.get("remark") or ""
ssl_remark = props.get("ssl_remark") or ""
ssl_status = props.get("ssl_status") or 0
try:
host_id = int(host_id)
except:
self.finish_json(1001, "提交参数异常,请检查请求参数")
return
if not host_id and not domain and not name:
self.finish_json(1001, "缺少必填项")
return
params = {"url": url, "status": status, "username": username, "password": password,
"remark": remark}
if ssl_remark:
log.i("ssl_remark")
params.update({"ssl_remark": ssl_remark})
if ssl_status:
log.i("ssl_status")
params.update({"ssl_status": ssl_status})
if host_id:
plugin.update("tp_remote_shop_bind", params, {"host_id": host_id})
else:
plugin.update("tp_remote_shop_bind", params, {"domain": domain, "name": name})
self.finish_json(0, data=[{}])
except:
info = traceback.format_exc()
log.e("设备详情,异常信息:{}".format(info))
class ShopBindHandler(TPBasePluginHandler):
def req_parse(self, required: tuple = ()):
self.parse = reqparse.RequestParser()
self.parse.add_argument("host_id", type=int, help='绑定设备id', required=True, trim=True)
self.parse.add_argument("name", type=str, help='商城名称', required=True, trim=True)
self.parse.add_argument("domain", type=str, help='商城域名', required=True, trim=True)
self.parse.add_argument("sub_domain", type=str, help='商城二级域名', trim=True)
args = self.parse.parse_args(req=self.get_payload())
return args
class ShopBindHandler(TPBasePluginHandler):
async def post(self):
try:
props = self.get_payload()
host_id = props.get("host_id") or 0
name = props.get("name") or ""
domain = props.get("domain") or ""
sub_domain = props.get("sub_domain") or ""
try:
host_id = int(host_id)
except:
self.finish_json(1001, "提交参数异常,请检查请求参数")
return
if not name or not domain:
self.finish_json(1001, "缺少必填项")
return
if not is_domain(domain) and not is_ipv4(domain):
args = self.req_parse()
# todo 特殊检查
if not is_domain(args.domain) and not is_ipv4(args.domain):
self.finish_json(1001, "请填写正确的域名信息")
return
if sub_domain and not is_domain(sub_domain):
if args.sub_domain and not is_domain(args.sub_domain):
self.finish_json(1001, "请填写正确的二级域名信息")
return
items = plugin.query_one("remote_shop_bind", ['name', 'domain', 'url', 'status'], {"host_id": host_id})
items = plugin.query_one("remote_shop_bind", ['name', 'domain', 'url', 'status'], {"host_id": args.host_id})
# 判断 IP
if items:
try:
resp = requests.get("http://{}".format(domain))
resp = requests.get("http://{}".format(args.domain))
code = resp.status_code
if code == 200 and '用户中心' in resp.content and '登录' in resp.content:
......@@ -921,18 +801,18 @@ class ShopBindHandler(TPBasePluginHandler):
code = 0
plugin.update("tp_remote_shop_bind",
{"name": name, "domain": domain, "status": 1, "sub_domain": sub_domain},
{"host_id": host_id})
{"name": args.name, "domain": args.domain, "status": 1, "sub_domain": args.sub_domain},
{"host_id": args.host_id})
items = plugin.query_one("remote_host", ['ip', 'username', 'password'], {"id": host_id, })
items = plugin.query_one("remote_host", ['ip', 'username', 'password'], {"id": args.host_id, })
password = des_descrypt(items.get("password", "")).decode()
cmd = execute_auto_install_script(items.get("ip", ""), items.get("username", ""), password, domain,
name, sub_domain)
cmd = execute_auto_install_script(items.get("ip", ""), items.get("username", ""), password, args.domain,
args.name, args.sub_domain)
log.i("自动部署商城:{}".format(cmd))
self.finish_json(0)
return
items = plugin.query_one("host", ['os_type'], {"id": host_id})
items = plugin.query_one("host", ['os_type'], {"id": args.host_id})
if not items:
self.finish_json(1003, "绑定主机不存在")
return
......@@ -941,15 +821,16 @@ class ShopBindHandler(TPBasePluginHandler):
self.finish_json(1003, "仅支持Linux主机进行绑定")
return
args = {"host_id": host_id, "name": name, "domain": domain, "status": 0, "sub_domain": sub_domain}
err, info = plugin.add_shop_bind(self, args)
data = {"host_id": args.host_id, "name": args.name, "domain": args.domain, "status": 0,
"sub_domain": args.sub_domain}
err, info = plugin.add_shop_bind(self, data)
if err == TPE_OK:
self.finish_json(0, "成功")
# finish 调用商城自动部署
items = plugin.query_one("remote_host", ['ip', 'username', 'password'], {"id": host_id, })
items = plugin.query_one("remote_host", ['ip', 'username', 'password'], {"id": args.host_id, })
password = des_descrypt(items.get("password", "")).decode()
cmd = execute_auto_install_script(items.get("ip", ""), items.get("username", ""), password, domain,
name, sub_domain)
cmd = execute_auto_install_script(items.get("ip", ""), items.get("username", ""), password, args.domain,
args.name, args.sub_domain)
log.i("自动部署商城:{}".format(cmd))
else:
self.finish_json(1002, "绑定商城信息失败")
......@@ -957,51 +838,6 @@ class ShopBindHandler(TPBasePluginHandler):
info = traceback.format_exc()
log.e("设备详情,异常信息:{}".format(info))
async def put(self):
try:
props = self.get_payload()
host_id = props.get("host_id") or 0
name = props.get("name") or ""
domain = props.get("domain") or ""
try:
host_id = int(host_id)
except:
self.finish_json(1001, "提交参数异常,请检查请求参数")
return
if not host_id or not name or not domain:
self.finish_json(1001, "缺少必填项")
return
if not is_domain(domain) and not is_ipv4(domain):
self.finish_json(1001, "请填写正确的域名信息")
return
items = plugin.query_one("remote_shop_bind", ['name', 'domain', 'url', 'status'], {"host_id": host_id})
# status = items.get("status", 0)
# 实时判断商城状态
if not items:
self.finish_json(1003, "绑定主机不存在")
return
try:
resp = requests.get("http://{}".format(domain))
code = resp.status_code
if code == 200 and '用户中心' in resp.content and '登录' in resp.content:
plugin.update("tp_remote_shop_bind", {"status": 1}, {"host_id": host_id})
self.finish_json(1021, "运行中商城,不可变更")
return
except:
code = 0
plugin.update("tp_remote_shop_bind", {"name": name, "domain": domain}, {"host_id": host_id})
self.finish_json(0)
except:
info = traceback.format_exc()
log.e("设备详情,异常信息:{}".format(info))
class PasswordUpdateHandler(TPBasePluginHandler):
@tornado.gen.coroutine
......@@ -1071,7 +907,7 @@ class PasswordUpdateHandler(TPBasePluginHandler):
class HostMonitorHandler(TPBasePluginHandler):
async def post(self):
async def post(self, required: tuple = ()):
try:
props = self.get_payload()
ip = props.get("ip") or ""
......
from copy import deepcopy
try:
from collections.abc import MutableSequence
except ImportError:
from collections import MutableSequence
from werkzeug.datastructures import MultiDict, FileStorage
from werkzeug import exceptions
import decimal
import six
class Namespace(dict):
def __getattr__(self, name):
try:
return self[name]
except KeyError:
raise AttributeError(name)
def __setattr__(self, name, value):
self[name] = value
_friendly_location = {
u'json': u'the JSON body',
u'form': u'the post body',
u'args': u'the query string',
u'values': u'the post body or the query string',
u'headers': u'the HTTP headers',
u'cookies': u'the request\'s cookies',
u'files': u'an uploaded file',
}
text_type = lambda x: six.text_type(x)
class Argument(object):
"""
:param name: Either a name or a list of option strings, e.g. foo or
-f, --foo.
:param default: The value produced if the argument is absent from the
request.
:param dest: The name of the attribute to be added to the object
returned by :meth:`~reqparse.RequestParser.parse_args()`.
:param bool required: Whether or not the argument may be omitted (optionals
only).
:param action: The basic type of action to be taken when this argument
is encountered in the request. Valid options are "store" and "append".
:param ignore: Whether to ignore cases where the argument fails type
conversion
:param type: The type to which the request argument should be
converted. If a type raises an exception, the message in the
error will be returned in the response. Defaults to :class:`unicode`
in python2 and :class:`str` in python3.
:param location: The attributes of the :class:`flask.Request` object
to source the arguments from (ex: headers, args, etc.), can be an
iterator. The last item listed takes precedence in the result set.
:param choices: A container of the allowable values for the argument.
:param help: A brief description of the argument, returned in the
response when the argument is invalid. May optionally contain
an "{error_msg}" interpolation token, which will be replaced with
the text of the error raised by the type converter.
:param bool case_sensitive: Whether argument values in the request are
case sensitive or not (this will convert all values to lowercase)
:param bool store_missing: Whether the arguments default value should
be stored if the argument is missing from the request.
:param bool trim: If enabled, trims whitespace around the argument.
:param bool nullable: If enabled, allows null value in argument.
"""
def __init__(self, name, default=None, dest=None, required=False,
ignore=False, type=text_type, location=('json', 'values',),
choices=(), action='store', help=None, operators=('=',),
case_sensitive=True, store_missing=True, trim=False,
nullable=True):
self.name = name
self.default = default
self.dest = dest
self.required = required
self.ignore = ignore
self.location = location
self.type = type
self.choices = choices
self.action = action
self.help = help
self.case_sensitive = case_sensitive
self.operators = operators
self.store_missing = store_missing
self.trim = trim
self.nullable = nullable
def __str__(self):
if len(self.choices) > 5:
choices = self.choices[0:3]
choices.append('...')
choices.append(self.choices[-1])
else:
choices = self.choices
return 'Name: {0}, type: {1}, choices: {2}'.format(self.name, self.type, choices)
def __repr__(self):
return "{0}('{1}', default={2}, dest={3}, required={4}, ignore={5}, location={6}, " \
"type=\"{7}\", choices={8}, action='{9}', help={10}, case_sensitive={11}, " \
"operators={12}, store_missing={13}, trim={14}, nullable={15})".format(
self.__class__.__name__, self.name, self.default, self.dest, self.required, self.ignore, self.location,
self.type, self.choices, self.action, self.help, self.case_sensitive,
self.operators, self.store_missing, self.trim, self.nullable)
def source(self, request):
"""Pulls values off the request in the provided location
:param request: The flask request object to parse arguments from
"""
if isinstance(self.location, six.string_types):
value = getattr(request, self.location, MultiDict())
if callable(value):
value = value()
if value is not None:
return value
else:
values = MultiDict()
if isinstance(request, dict):
values.update(request)
# for l in self.location:
# value = getattr(request, l, None)
# if callable(value):
# value = value()
# if value is not None:
# values.update(value)
return values
return MultiDict()
def convert(self, value, op):
# Don't cast None
if value is None:
if self.nullable:
return None
else:
raise ValueError('Must not be null!')
# and check if we're expecting a filestorage and haven't overridden `type`
# (required because the below instantiation isn't valid for FileStorage)
elif isinstance(value, FileStorage) and self.type == FileStorage:
return value
try:
return self.type(value, self.name, op)
except TypeError:
try:
if self.type is decimal.Decimal:
return self.type(str(value))
else:
return self.type(value, self.name)
except TypeError:
return self.type(value)
def handle_validation_error(self, error, bundle_errors):
"""Called when an error is raised while parsing. Aborts the request
with a 400 status and an error message
:param error: the error that was raised
:param bundle_errors: do not abort when first error occurs, return a
dict with the name of the argument and the error message to be
bundled
"""
error_str = six.text_type(error)
error_msg = self.help.format(error_msg=error_str) if self.help else error_str
msg = {self.name: error_msg}
raise Exception(msg)
def parse(self, request, bundle_errors=False):
"""Parses argument value(s) from the request, converting according to
the argument's type.
:param request: The flask request object to parse arguments from
:param bundle_errors: Do not abort when first error occurs, return a
dict with the name of the argument and the error message to be
bundled
"""
source = self.source(request)
results = []
# Sentinels
_not_found = False
_found = True
for operator in self.operators:
name = self.name + operator.replace("=", "", 1)
if name in source:
# Account for MultiDict and regular dict
if hasattr(source, "getlist"):
values = source.getlist(name)
else:
values = source.get(name)
if not (isinstance(values, MutableSequence) and self.action == 'append'):
values = [values]
for value in values:
if hasattr(value, "strip") and self.trim:
value = value.strip()
if hasattr(value, "lower") and not self.case_sensitive:
value = value.lower()
if hasattr(self.choices, "__iter__"):
self.choices = [choice.lower()
for choice in self.choices]
try:
value = self.convert(value, operator)
except Exception as error:
if self.ignore:
continue
return self.handle_validation_error(error, bundle_errors)
if self.choices and value not in self.choices:
self.handle_validation_error(
ValueError(u"{0} is not a valid choice".format(
value)), bundle_errors)
# todo 为解析参数
# if name in request.unparsed_arguments:
# request.unparsed_arguments.pop(name)
results.append(value)
if not results and self.required:
if isinstance(self.location, six.string_types):
error_msg = u"Missing required parameter in {0}".format(
_friendly_location.get(self.location, self.location)
)
else:
friendly_locations = [_friendly_location.get(loc, loc)
for loc in self.location]
error_msg = u"Missing required parameter in {0}".format(
' or '.join(friendly_locations)
)
self.handle_validation_error(ValueError(error_msg), bundle_errors)
if not results:
if callable(self.default):
return self.default(), _not_found
else:
return self.default, _not_found
if self.action == 'append':
return results, _found
if self.action == 'store' or len(results) == 1:
return results[0], _found
return results, _found
class RequestParser(object):
"""Enables adding and parsing of multiple arguments in the context of a
single request. Ex::
from flask_restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument('foo')
parser.add_argument('int_bar', type=int)
args = parser.parse_args()
:param bool trim: If enabled, trims whitespace on all arguments in this
parser
:param bool bundle_errors: If enabled, do not abort when first error occurs,
return a dict with the name of the argument and the error message to be
bundled and return all validation errors
"""
def __init__(self, argument_class=Argument, namespace_class=Namespace,
trim=False, bundle_errors=False):
self.args = []
self.argument_class = argument_class
self.namespace_class = namespace_class
self.trim = trim
self.bundle_errors = bundle_errors
def add_argument(self, *args, **kwargs):
"""Adds an argument to be parsed.
Accepts either a single instance of Argument or arguments to be passed
into :class:`Argument`'s constructor.
See :class:`Argument`'s constructor for documentation on the
available options.
"""
if len(args) == 1 and isinstance(args[0], self.argument_class):
self.args.append(args[0])
else:
self.args.append(self.argument_class(*args, **kwargs))
# Do not know what other argument classes are out there
if self.trim and self.argument_class is Argument:
# enable trim for appended element
self.args[-1].trim = kwargs.get('trim', self.trim)
return self
def parse_args(self, req, strict=False):
"""Parse all arguments from the provided request and return the results
as a Namespace
:param req: Can be used to overwrite request from Flask
:param strict: if req includes args not in parser, throw 400 BadRequest exception
:param http_error_code: use custom error code for `flask_restful.abort()`
"""
namespace = self.namespace_class()
# A record of arguments not yet parsed; as each is found
# among self.args, it will be popped out
# todo 严格筛选处理
unparsed_arguments = dict(self.argument_class('').source(req)) if strict else {}
errors = {}
for arg in self.args:
value, found = arg.parse(req, self.bundle_errors)
if isinstance(value, ValueError):
errors.update(found)
found = None
if found or arg.store_missing:
namespace[arg.dest or arg.name] = value
if errors:
raise Exception(errors)
if strict and unparsed_arguments:
raise exceptions.BadRequest('Unknown arguments: %s'
% ', '.join(req.unparsed_arguments.keys()))
return namespace
def copy(self):
""" Creates a copy of this RequestParser with the same set of arguments """
parser_copy = self.__class__(self.argument_class, self.namespace_class)
parser_copy.args = deepcopy(self.args)
parser_copy.trim = self.trim
parser_copy.bundle_errors = self.bundle_errors
return parser_copy
def replace_argument(self, name, *args, **kwargs):
""" Replace the argument matching the given name with a new version. """
new_arg = self.argument_class(name, *args, **kwargs)
for index, arg in enumerate(self.args[:]):
if new_arg.name == arg.name:
del self.args[index]
self.args.append(new_arg)
break
return self
def remove_argument(self, name):
""" Remove the argument matching the given name. """
for index, arg in enumerate(self.args[:]):
if name == arg.name:
del self.args[index]
break
return self
if __name__ == '__main__':
parse = RequestParser()
parse.add_argument("host_id", type=int, choices=[1, 2])
args = parse.parse_args(req={"host_id": '1'})
print(args)
......@@ -97,18 +97,15 @@ def auto_install_bt(ip, username, password, site, webname, sub="", host_id=0):
update_shop_info(site, webname, remark="宝塔初始化完成", url=url, username=username, password=password)
print("install_bt", result)
i = 0
while i < 2:
print('*************************************************************************************')
for i in range(2):
result = install_shop(ssh, site, ip, webname, sub)
print("install_shop", result)
i += 1
if "商城已存在" in result:
print("商城已存在")
update_shop_info(site, webname, host_id, status=1, remark="商城已存在", url=url, username=username,
password=password)
break
ssl_remark, ssl_status = "", 0
if "配置商城成功" in result or "商城已存在" in result:
print("更新商城信息")
if "申请HTTPS证书成功" in result or "HTTPS证书已存在" in result:
......@@ -118,9 +115,6 @@ def auto_install_bt(ip, username, password, site, webname, sub="", host_id=0):
ssl_remark = between(result, "new ssl response:[", "]\n")
ssl_remark = json.loads(ssl_remark)['msg'][0]
ssl_status = 2
else:
ssl_remark = ""
ssl_status = 0
update_shop_info(site, webname, host_id, status=1, remark="商城部署成功", url=url, username=username,
password=password, ssl_remark=ssl_remark, ssl_status=ssl_status)
......
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