Commit 3b512088 authored by tarak.li's avatar tarak.li

添加证书相关判断

parent 981cc02a
......@@ -316,13 +316,14 @@ class AppConfig(BaseAppConfig):
self.set_default('plugin::consul', '127.0.0.1', 'consul=http://172.30.10.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')
def _on_get_save_info(self):
return [
{'common': ['ip', 'port', 'log-file', 'log-level', 'debug-mode', 'core-server-rpc']},
{'database': ['type', 'sqlite-file', 'mysql-host', 'mysql-port', 'mysql-db', 'mysql-prefix', 'mysql-user',
'mysql-password']},
{"plugin": ["core_host", "consul", "release_ip", "server"]}
{"plugin": ["core_host", "consul", "release_ip", "server", "manager_host"]}
]
def _on_load(self, cfg_parser):
......@@ -413,6 +414,10 @@ class AppConfig(BaseAppConfig):
if _tmp_str is not None:
self.set_kv('plugin::server', _tmp_str)
_tmp_str = _sec.get('manager_host', None)
if _tmp_str is not None:
self.set_kv('plugin::manager_host', _tmp_str)
_log_file, ok = self.get_str('common::log-file')
if ok and _log_file:
self.log_path = os.path.abspath(os.path.dirname(_log_file))
......
......@@ -2,7 +2,9 @@
import argparse
import hashlib
import json
import os
import time
import traceback
import requests
......@@ -59,7 +61,7 @@ def add_site(site, host):
"webname": webname, "ftp": "false", "sql": "true",
"address": "localhost", "codeing": "utf8"}
resp = session.post(url, data=data)
print(resp.content)
print("add_site", resp.content)
# 正常添加返回
# {"ftpStatus": false, "databaseUser": "sql121_196_33_88", "databaseStatus": true, "databasePass": "123456", "siteId": 6, "siteStatus": true}
# 异常添加返回
......@@ -74,12 +76,12 @@ def del_site(ip, site):
resp = session.post(url, data)
for item in resp.json().get("data", []):
if item.get("name") == site or not site:
print("删除站点:{}".format(item.get("name", "")))
print("delete site:{}".format(item.get("name", "")))
url = "http://{}/site?action=DeleteSite".format(ip)
# data = "id=1&webname=site"
data = {"database": 1, "path": 1, "webname": site, "id": item.get("id")}
resp = session.post(url, data)
print(resp.content)
print("delete site response", resp.content)
def install_dbshop(site, host):
......@@ -92,8 +94,6 @@ def install_dbshop(site, host):
i = 0
while True:
resp = session.post(url, data=data)
print(url, data, resp.content)
if resp.status_code == 200:
break
i += 1
......@@ -145,7 +145,7 @@ def shop_config(host, site, webname="DBShop电子商务系统"):
i = 0
while True:
resp = session.post(url, data=data)
print(url, data, resp.content)
print("check db", url, data, resp.content)
if resp.text != "false":
break
......@@ -205,8 +205,7 @@ def check_all_domain(ip):
for domain in get_domain(ip, id):
if check_shop(domain):
is_exists_shop_id = id
print("{} 已存在商城 {}".format(domain, name))
print("{} 商城已存在 {}".format(domain, name))
break
if is_exists_shop_id:
......@@ -364,7 +363,7 @@ def add_site_domain(id, ip, site, webname):
url = "http://{}/site?action=AddDomain".format(ip)
data = {"domain": site, "webname": webname, "id": id}
resp = session.post(url, data)
print(resp.content)
print("add sub domain", resp.content)
return
......@@ -389,22 +388,118 @@ def add_nginx(ip, id, site):
return True
def run(ip, path, user, pwd, site, webname):
print(login(path, user, pwd, ip))
print("完成宝塔登录配置")
def check_ssl(ip, sub_domain):
# 获取已部署证书
url = "http://{}/ssl?action=GetCertList".format(ip)
resp = session.post(url)
for item in resp.json():
if item.get("subject") == sub_domain:
return True
return False
def set_old_ssl(ip, site, cert_name):
# 部署已存在证书
url = "http://{}/ssl?action=SetCertToSite".format(ip)
data = {"certName": cert_name, "siteName": site}
resp = session.post(url, data)
print("set old ssl", resp.content)
return True
def ssl_status(ip, site):
url = "http://{}/site?action=GetSSL".format(ip)
data = {"siteName": site}
resp = session.post(url, data)
# status 是否部署证书 ,httpTohttps 是否使用https
response = resp.json()
if response['httpTohttps']:
print("ssl_status:{}".format(response['cert_data']['subject']))
return True
return False
def start_https(ip, site):
url = "http://{}/site?action=HttpToHttps".format(ip)
data = {"siteName": site}
resp = session.post(url, data)
print("start HTTPS", resp.content)
if check_shop(site):
print("商城已存在")
def set_ssl(ip, site, id, sub_domain):
# 已部署证书的不再部署
if ssl_status(ip, site):
return
shop_id, name = check_all_domain(ip)
if shop_id:
print("商城已存在", shop_id, "name", name)
add_site_domain(shop_id, ip, site, webname)
add_nginx(ip, shop_id, name)
if check_ssl(ip, sub_domain):
print("HTTPS证书已存在")
set_old_ssl(ip, site, sub_domain)
start_https(ip, site)
return
install_shop(ip, site, webname)
url = "http://{}/acme?action=get_account_info".format(ip)
data = {"action": "get_account_info"}
resp = session.post(url, data)
url = "http://{}/site?action=GetSiteDomains".format(ip)
data = {"id": id}
resp = session.post(url, data)
url = "http://{}/acme?action=apply_cert_api".format(ip)
data = {"domains": '["{}"]'.format(sub_domain), "auth_type": "http", "auth_to": id, "auto_wildcard": 0, "id": id}
resp = session.post(url, data)
resp.encoding = "utf-8"
cert = resp.json()
print("apply_cert_api", resp.json())
# {"status": false, "msg": ["签发失败,该域名['pay.xamsmsm.com: see https']超出了每周的重复签发次数限制! ", {"status": 429, "type": "urn:ietf:params:acme:error:rateLimited", "detail": "Error creating new order :: too many certificates already issued for exact set of domains: pay.xamsmsm.com: see https://letsencrypt.org/docs/rate-limits/"}]}
if resp.json().get("status", False):
print("申请HTTPS证书成功")
url = "http://{}/site?action=SetSSL".format(ip)
# /www/server/panel/vhost/ssl/pay.xamsmsm.com/fullchain.pem
# /www/server/panel/vhost/ssl/pay.xamsmsm.com/privkey.pem
data = {"type": 1, "siteName": site,
"key": cert['private_key'],
"csr": cert['cert'] + cert['root']}
resp = session.post(url, data)
print("set ssl response", resp.content)
start_https(ip, site)
else:
if isinstance(resp.json()['msg'], list):
print("new ssl response:[%s]" % (resp.content))
print("申请HTTPS证书失败")
def run(ip, path, user, pwd, site, webname, sub_domain=""):
try:
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, site, name)
if sub_domain:
add_site_domain(shop_id, ip, sub_domain, name)
add_nginx(ip, shop_id, name)
set_ssl(ip, name, shop_id, sub_domain)
return
install_shop(ip, site, webname)
if sub_domain:
shop_id, name = check_all_domain(ip)
if shop_id:
add_site_domain(shop_id, ip, ip.replace(":8888", ""), name)
print("商城已存在", shop_id, "name", name)
add_site_domain(shop_id, ip, sub_domain, name)
add_nginx(ip, shop_id, name)
set_ssl(ip, name, shop_id, sub_domain)
except:
print("error:{}".format(str(traceback.format_exc())))
def main():
......@@ -416,19 +511,19 @@ def main():
parser.add_argument("-p", "--pwd", help="password")
parser.add_argument("-s", "--site", help="site info")
parser.add_argument("-w", "--webname", help="webname")
parser.add_argument("--sub", help="sub webname")
args = parser.parse_args()
print(args)
ip = "{}:8888".format(args.ip)
print(args.path, args.user, args.pwd, args.site)
path = args.path or ''
run(ip, path, args.user, args.pwd, args.site, args.webname)
run(ip, path, args.user, args.pwd, args.site, args.webname, args.sub or "")
if __name__ == '__main__':
main()
# run("121.196.33.88:8888", path='e7393047', pwd='93395d57', site='www.gingboutrade.com', user='oag8vyv9',
# webname='测试')
# check_shop("121.196.33.88")
# update_nginx("121.196.33.88:8888", "121.196.33.88")
# 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")
......@@ -25,6 +25,6 @@ host=$(echo ${var#*8888/} | cut -c 1-8)
username=$(echo ${var#*username: } | cut -c 1-8)
password=$(echo ${var#*password: } | cut -c 1-8)
#/usr/bin/python /root/auto_install.py -u $username -p $password -s $1 --path $host --ip $2 -w $3 > /tmp/load.log 2>&1
echo -u $username -p $password -s $1 --path $host --ip $2 -w $3
/usr/bin/python /root/auto_install.py -u $username -p $password -s $1 --path $host --ip $2 -w $3
echo -u $username -p $password -s $1 --path $host --ip $2 -w $3 --sub $4
/usr/bin/python /root/auto_install.py -u $username -p $password -s $1 --path $host --ip $2 -w $3 --sub $4
......@@ -92,11 +92,14 @@ def is_ipv4(address):
return True if ipv4_regex.match(address) else False
def execute_auto_install_script(ip, usename, password, site, webname, host_id):
def execute_auto_install_script(ip, usename, password, site, webname, sub_domain):
path = os.path.dirname(os.path.abspath(__file__))
cmd = 'nohup /usr/bin/python3 {}/script.py --ip {} -u {} -p {} -s {} -w {} >> auto.out &'.format(path, ip, usename,
password,
site, webname)
cmd = 'nohup /usr/bin/python3 {}/script.py --ip {} -u {} -p {} -s {} -w {} --sub {}>> /auto.out &'.format(path, ip,
usename,
password,
site,
webname,
sub_domain)
os.system(cmd)
return cmd
......@@ -835,6 +838,8 @@ class ShopInfoHandler(TPBasePluginHandler):
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:
......@@ -845,14 +850,19 @@ class ShopInfoHandler(TPBasePluginHandler):
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",
{"url": url, "status": status, "username": username, "password": password,
"remark": remark}, {"host_id": host_id})
plugin.update("tp_remote_shop_bind", params, {"host_id": host_id})
else:
plugin.update("tp_remote_shop_bind",
{"url": url, "status": status, "username": username, "password": password,
"remark": remark}, {"domain": domain, "name": name})
plugin.update("tp_remote_shop_bind", params, {"domain": domain, "name": name})
self.finish_json(0, data=[{}])
except:
info = traceback.format_exc()
......@@ -881,6 +891,10 @@ class ShopBindHandler(TPBasePluginHandler):
self.finish_json(1001, "请填写正确的域名信息")
return
if not is_domain(sub_domain):
self.finish_json(1001, "请填写正确的二级域名信息")
return
items = plugin.query_one("remote_shop_bind", ['name', 'domain', 'url', 'status'], {"host_id": host_id})
# 判断 IP
......@@ -902,7 +916,7 @@ class ShopBindHandler(TPBasePluginHandler):
items = plugin.query_one("remote_host", ['ip', 'username', 'password'], {"id": host_id, })
password = des_descrypt(items.get("password", "")).decode()
cmd = execute_auto_install_script(items.get("ip", ""), items.get("username", ""), password, domain,
name, host_id)
name, sub_domain)
log.i("自动部署商城:{}".format(cmd))
self.finish_json(0)
return
......@@ -924,7 +938,7 @@ class ShopBindHandler(TPBasePluginHandler):
items = plugin.query_one("remote_host", ['ip', 'username', 'password'], {"id": host_id, })
password = des_descrypt(items.get("password", "")).decode()
cmd = execute_auto_install_script(items.get("ip", ""), items.get("username", ""), password, domain,
name, host_id)
name, sub_domain)
log.i("自动部署商城:{}".format(cmd))
else:
self.finish_json(1002, "绑定商城信息失败")
......@@ -963,14 +977,14 @@ class ShopBindHandler(TPBasePluginHandler):
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
if code == 200:
plugin.update("tp_remote_shop_bind", {"status": 1}, {"host_id": host_id})
self.finish_json(1021, "运行中商城,不可变更")
return
plugin.update("tp_remote_shop_bind", {"name": name, "domain": domain}, {"host_id": host_id})
self.finish_json(0)
except:
......
# coding: utf-8
import argparse
import json
import os
from concurrent.futures.thread import ThreadPoolExecutor
......@@ -22,17 +23,17 @@ def between(source, begin_str, end_str, start=''):
def update_shop_info(site, webname, host_id=0, status=2, **kwargs):
# url = "http://127.0.0.1:7190/plugin/shop_info"
url = "http://127.0.0.1:7190/plugin/shop_info"
data = {"domain": site, "name": webname, "host_id": host_id, "status": status}
if kwargs:
data = dict(data, **kwargs)
print(data)
url = "http://172.30.10.104:7190/plugin/shop_info"
# url = "http://172.30.10.204:7190/plugin/shop_info"
executor.submit(requests.put, url=url, json=data, )
def install_shop(ssh, site, ip, webname):
stdin, stdout, stderr = ssh.exec_command("sh /root/install-shop.sh {} {} {}".format(site, ip, webname, ))
def install_shop(ssh, site, ip, webname, sub=""):
stdin, stdout, stderr = ssh.exec_command("sh /root/install-shop.sh {} {} {} '{}'".format(site, ip, webname, sub))
# 获取命令结果
res, err = stdout.read(), stderr.read()
......@@ -74,7 +75,7 @@ def push_file(ip, username, password):
p.close()
def auto_install_bt(ip, username, password, site, webname, host_id=0):
def auto_install_bt(ip, username, password, site, webname, sub="", host_id=0):
transport = paramiko.Transport((ip, 22))
try:
push_file(ip, username, password)
......@@ -94,7 +95,7 @@ def auto_install_bt(ip, username, password, site, webname, host_id=0):
i = 0
while i < 2:
print('*************************************************************************************')
result = install_shop(ssh, site, ip, webname)
result = install_shop(ssh, site, ip, webname, sub)
print(result)
i += 1
......@@ -104,13 +105,21 @@ def auto_install_bt(ip, username, password, site, webname, host_id=0):
password=password)
break
if "配置商城成功" in result:
if "配置商城成功" in result or "商城已存在" in result:
print("更新商城信息")
if "申请HTTPS证书成功" in result or "HTTPS证书已存在" in result:
ssl_remark = "申请HTTPS证书成功"
ssl_status = 1
elif "申请HTTPS证书失败" in result:
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)
elif "商城已存在" in result:
update_shop_info(site, webname, host_id, status=1, remark="商城已存在", url=url, username=username,
password=password)
password=password, ssl_remark=ssl_remark, ssl_status=ssl_status)
else:
update_shop_info(site, webname, host_id, status=3, remark="商城部署失败,请重试", url=url, username=username,
password=password)
......@@ -131,14 +140,15 @@ def main():
parser.add_argument("-p", "--pwd", help="password")
parser.add_argument("-s", "--site", help="site info")
parser.add_argument("-w", "--webname", help="webname")
parser.add_argument("--sub", help="sub webname")
args = parser.parse_args()
print(args)
auto_install_bt(args.ip, args.user, args.pwd, args.site, args.webname)
auto_install_bt(args.ip, args.user, args.pwd, args.site, args.webname, args.sub or "")
if __name__ == '__main__':
# push_file('121.196.33.88', 'root', 'Aa123456')
# auto_install_bt('34.92.159.68', 'root', 'Aa@123321', "34.92.159.68", "")
# auto_install_bt('34.92.159.68', 'root', 'Aa@123321', "34.92.159.68", "测试商城", "test.xlfamily.top")
# update_shop_info(site="www.test.com", webname="测试商城1", test="")
main()
......@@ -420,12 +420,13 @@ def add_shop_bind(handler, args):
_time_now = tp_timestamp_utc_now()
operator = handler.get_current_user()
sql = 'INSERT INTO `tp_remote_shop_bind` (host_id, name, domain, url, status, username, password, remark, create_time, create_by, update_time, update_by) VALUES ' \
'({host_id}, "{name}", "{domain}", "{url}", {status}, "{username}", "{password}", "{remark}", "{create_time}", "{create_by}", "{update_time}", "{update_by}");' \
sql = 'INSERT INTO `tp_remote_shop_bind` (host_id, name, domain, url, status, username, password, remark, create_time, create_by, update_time, update_by,sub_domain) VALUES ' \
'({host_id}, "{name}", "{domain}", "{url}", {status}, "{username}", "{password}", "{remark}", "{create_time}", "{create_by}", "{update_time}", "{update_by}", "{sub_domain}");' \
''.format(host_id=args.get("host_id", 0), name=args.get("name", ""), domain=args.get("domain", ""),
url=args.get("url", ""), status=args.get("status", 0), username=args.get("username", ""),
password=args.get("password", ""), remark=args.get("remark", ""), create_time=_time_now,
create_by=operator['id'], update_time=_time_now, update_by=operator['id'], )
create_by=operator['id'], update_time=_time_now, update_by=operator['id'],
sub_domain=args.get("sub_domain", ""))
db_ret = db.exec(sql)
if not db_ret:
......
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