# coding: utf-8
# +-------------------------------------------------------------------
# | 宝塔Linux面板
# +-------------------------------------------------------------------
# | Copyright (c) 2015-2099 宝塔软件(http://bt.cn) All rights reserved.
# +-------------------------------------------------------------------
# | Author:  沐落 <cjx@bt.cn>
# +-------------------------------------------------------------------

# ------------------------------
# 工具箱
# ------------------------------
import sys, os, shutil
import traceback

panelPath = os.getenv("BT_PANEL")
if not panelPath:
    panelPath = os.path.dirname(os.path.abspath(__file__))
    os.environ['BT_PANEL'] = panelPath

os.chdir(panelPath);
sys.path.insert(0, panelPath + "/class/")
import time, json, psutil

try:
    import public
except:
    pass


def set_mysql_root(password):
    """
    设置MySQL密码
    @password 新密码
    """
    import db, os, pymysql, re
    from subprocess import PIPE
    sql = db.Sql()

    public.kill('mysqld.exe')
    try:
        fname = re.search('([MySQL|MariaDB-]+\d+\.\d+)', public.get_server_path('mysql')).groups()[0]
        _setup_path = public.GetConfigValue('setup_path') + '/mysql/' + fname

        shell = "START /b {}/bin/mysqld.exe --defaults-file={}/my.ini --skip-grant-tables".format(_setup_path, _setup_path)
        if fname.find('8.0') >= 0:
            shell = "START /b {}/bin/mysqld.exe --defaults-file={}/my.ini --console --skip-grant-tables --shared-memory".format(_setup_path, _setup_path);
        os.system(shell)
        while not public.process_exists('mysqld.exe'):
            time.sleep(0.2)
        time.sleep(6)

        if fname.find("5.7") >= 0 or fname.find("8.0") >= 0:
            c_shell = "{}/bin/mysql.exe -uroot -e \"FLUSH PRIVILEGES;update mysql.user set authentication_string='' where user='root' and (host='127.0.0.1' or host='localhost');alter user 'root'@'localhost' identified by '{}';drop user 'root'@'127.0.0.1';create user 'root'@'127.0.0.1' identified by '{}';FLUSH PRIVILEGES;\"".format(
                _setup_path, password, password)
        elif fname.find('10.5') >= 0 or fname.find('10.4') >= 0:
            c_shell = "{}/bin/mysql.exe -uroot -e \"FLUSH PRIVILEGES;alter user 'root'@'localhost' identified by '{}';alter user 'root'@'127.0.0.1' identified by '{}';FLUSH PRIVILEGES;\"".format(
                _setup_path, password, password)
        else:
            c_shell = "{}/bin/mysql.exe -uroot -e \"FLUSH PRIVILEGES;UPDATE mysql.user set password=PASSWORD('{}') WHERE User='root';FLUSH PRIVILEGES;\"".format(_setup_path, password)

        ret = public.ExecShell(c_shell)
        if len(ret[1]) > 0:
            print("|-: " + ret[1]);
            print("|- 等待10秒后重试.");
            time.sleep(10)
            ret = public.ExecShell(c_shell)
            print(ret)

        print("|-MySQL新root密码: " + password);
    except:
        print(public.get_error_info())
        print("|-连接超时。MySQL的root密码修改失败. ");

    public.kill('mysqld.exe')
    time.sleep(1)
    public.set_server_status('mysql', 'start')
    result = sql.table('config').where('id=?', (1,)).setField('mysql_root', password)


def set_panel_pwd(password, ncli=False):
    """
    设置面板密码
    """
    import db
    sql = db.Sql()
    pwd = public.password_salt(public.md5(password), uid=1)

    result = sql.table('users').where('id=?', (1,)).setField('password', pwd)
    username = sql.table('users').where('id=?', (1,)).getField('username')
    if ncli:
        print("|-用户名: " + username)
        print("|-新密码: " + password)
    else:
        print(username)


def ClearRecycle_Bin():
    """
    清空回收站
    """
    import files
    f = files.files();
    f.Close_Recycle_bin(None);


def set_panel_default_dir(dir=None):
    """
    设置默认目录
    @dir 目录地址（默认为面板目录）
    """
    dir = panelPath[:2] + '/'
    if os.path.exists(dir):
        import db
        sql = db.Sql()
        backup_path = dir + 'backup'
        www_path = dir + 'wwwroot'

        sql.table('config').where('id=?', (1,)).setField('backup_path', backup_path)
        sql.table('config').where('id=?', (1,)).setField('sites_path', www_path)

        if not os.path.exists(backup_path): os.makedirs(backup_path)
        if not os.path.exists(www_path): os.makedirs(www_path)

        print("|-修改默认建站目录和默认备份目录成功")
        return;
    else:
        print("|-错误，目录不存在")
        return


def set_panel_username(username=None):
    """
    修改面板用户名
    @username 面板用户名，不可为admin，不可小于5位
    """
    import db
    sql = db.Sql()
    if username:
        if len(username) < 5:
            print("|-错误，用户名长度不能少于5位")
            return;
        if username in ['admin', 'root']:
            print("|-错误，不能使用过于简单的用户名")
            return;

        sql.table('users').where('id=?', (1,)).setField('username', username)
        print("|-新用户名: %s" % username)
        return;

    username = sql.table('users').where('id=?', (1,)).getField('username')
    if username == 'admin':
        username = public.GetRandomString(8).lower()
        sql.table('users').where('id=?', (1,)).setField('username', username)
    print('username: ' + username)


def auto_update_panel():
    """
    检查面板更新
    """
    data = {}
    data['uid'] = 0
    try:
        userInfo = json.loads(public.ReadFile('{}/data/userInfo.json'.format(panelPath)))
        data['uid'] = userInfo['uid']
    except:
        pass

    sUrl = public.GetConfigValue('home') + '/api/wpanel/updateWindows';
    updateInfo = json.loads(public.httpPost(sUrl, data));

    import platform
    py_version = platform.python_version()
    if updateInfo['py_version'] != py_version:
        public.writeFile("C:/Program Files/python/update.pl", "True")
        print('由于Python官方即将停止对{}版本的维护，Python版本即将升级，请按照以下方式升级'.format(py_version))
        print('1、下载安装包 s://download.bt.cn/win/panel/BtSoft.zip ')
        print('2、打开BtSoft.exe更新Python环境')

        print(
            '注意：如过Windows 2008无法正常运行面板，需要安装此补丁才能正常使用：wget https://download.bt.cn/win/panel/data/Windows6.1-KB2533623-x64.msu -O C:/KB2533623.msu -t 5 -T 60 && C:/KB2533623.msu')
        exit()

    version = updateInfo['version']
    if updateInfo['is_beta']: version = updateInfo['beta']['version']
    cVersion = public.version()
    print('当前面板版本:{},官方最新版本:{}'.format(cVersion, version))
    if version != cVersion:
        print('当前版本需要更新，正在升级到{}...'.format(version))
        shell = 'wget https://download.bt.cn/win/panel/data/setup.py -O C:/update.py -t 5 -T 60 && "C:\Program Files\python\python.exe" C:/update.py update_panel {}'.format(version)
        os.system(shell)
        if os.path.exists('C:/update.py'): os.remove('C:/update.py')
        os.system('bt restart')
    else:
        print('当前已经是最新版本，无需升级.')


def update_to():
    """
    更新面板到最新正式版
    """
    vpath = panelPath + '/data/panel.version'
    if os.path.exists(vpath): os.remove(vpath);
    RepPanel();
    return True


def RepPanel():
    """
    命令行修复面板
    """
    # 尝试删除本地hosts文件中的宝塔域名解析


    v4_file = '{}/data/v4.pl'.format(panelPath)
    if os.path.exists(v4_file):
        os.remove(v4_file)

    version = public.readFile(panelPath + '/data/panel.version')
    if not version: version = public.httpGet("https://www.bt.cn/api/wpanel/get_go_version?is_version=1")


    import panel_update
    update = panel_update.panel_update()
    ret = update.UpdatePanel(version)
    if not ret['status']:
        exit(ret['msg']);

    setupPath = os.getenv("BT_SETUP")
    # 修复配置
    conf_path = panelPath + '/config/config.json'
    if os.path.exists(conf_path):
        conf = public.readFile(conf_path).replace('[PATH]', setupPath.replace('\\', '/'))
        public.writeFile(conf_path, conf)

    # py_path = 'C:/Program Files/python/python.exe'
    # if public.get_server_status('btPanel') < 0:  public.ExecShell("\"{}\" {}/panel/runserver.py --startup auto install".format(py_path, setupPath))

    # if public.get_server_status('btTask') < 0: public.ExecShell("\"{}\" {}/panel/task.py --startup auto install".format(py_path, setupPath))

    os.system("bt restart")


def set_unzip(src, dist):
    """
    命令行解压文件
    """
    import zipfile
    zip_file = zipfile.ZipFile(src)
    for names in zip_file.namelist():
        zip_file.extract(names, dist)
    zip_file.close()


def get_panel_config(is_json=True):
    """
    获取面板配置(BtTools使用)
    @is_json 运行json返回还是|分割返回
    """
    import db
    data = {}
    data['url'] = public.GetLocalIp();
    sql = db.Sql()
    username = sql.table('users').where('id=?', (1,)).getField('username')
    data['username'] = username
    if is_json:
        print(json.dumps(data))
    else:
        print('|%s|%s|' % (data['username'], data['url']))


def set_panel_port(input_port):
    """
    修改面板端口并放行端口
    @input_port 要修改的端口
    """
    oldPort = public.readFile('data/port.pl');
    if int(oldPort) != int(input_port):
        import time
        public.writeFile('data/port.pl', str(input_port))
        ps = public.getMsg('PORT_CHECK_PS');

        # 放行新端口
        version = public.get_sys_version()
        shell = 'netsh firewall set portopening tcp %s "%s"' % (input_port, ps)
        if int(version[0]) == 6:
            shell = 'netsh advfirewall firewall add rule name="%s" dir=in action=allow protocol=tcp localport=%s' % (ps, input_port)
        public.ExecShell(shell)
        addtime = time.strftime('%Y-%m-%d %X', time.localtime())
        public.M('firewall').add('port,ps,addtime', (str(input_port), ps, addtime))

        # 删除老端口
        public.M('firewall').where("port=?", (oldPort,)).delete()
        shell = "netsh firewall delete portopening protocol=tcp port=" + str(oldPort)
        if int(version[0]) == 6:
            shell = "netsh advfirewall firewall delete rule name=all protocol=tcp localport=" + str(oldPort)
        public.ExecShell(shell)


def ClearSystem():
    """
    清理系统垃圾
    """
    count = total = 0
    print('=======================================================================')
    tmp_total, tmp_count = ClearSession()
    count += tmp_count
    total += tmp_total
    print('=======================================================================')
    tmp_total, tmp_count = ClearOther()
    count += tmp_count
    total += tmp_total
    print('=======================================================================')
    print('|-系统垃圾清理完成，共删除[' + str(count) + ']个文件,释放磁盘空间[' + public.to_size(total) + ']')


# 清理php_session文件
def ClearSession():
    spath = '{}/temp/session'.format(os.getenv("BT_SETUP"))
    total = count = 0
    import shutil
    print('|-正在清理PHP_SESSION ...')
    for d in os.listdir(spath):
        if d.find('sess_') == -1: continue
        filename = spath + '/' + d
        fsize = os.path.getsize(filename)
        print('|---[' + public.to_size(fsize) + '] del ' + filename),
        total += fsize
        if os.path.isdir(filename):
            shutil.rmtree(filename)
        else:
            os.remove(filename)
        count += 1
    print('|-已完成php_session的清理，删除[' + str(count) + ']个文件,共释放磁盘空间[' + public.to_size(total) + ']')
    return total, count


def ClearOther():
    """
    清理其它日志
    """
    spath = os.getenv("BT_SETUP")
    clearPath = [
        {'path': spath + '/temp', 'find': '.zip'}
    ]
    total = count = 0
    print('|-正在清理临时文件 ...')
    for c in clearPath:
        for d in os.listdir(c['path']):
            if d.find(c['find']) == -1: continue
            filename = c['path'] + '/' + d
            if os.path.isdir(filename): continue
            fsize = os.path.getsize(filename)
            print('|---[' + public.to_size(fsize) + '] del ' + filename),
            total += fsize
            os.remove(filename)
            count += 1

    print('|-已完成临时文件，删除[' + str(count) + ']个文件,共释放磁盘空间[' + public.to_size(total) + ']')
    return total, count


def check_python_version():
    # 检查Python版本
    # 下载官网python版本文件
    url = "https://download.bt.cn/win/panel_python_version"
    version = '3.8.6'
    res = None
    setup_path = os.getenv('BT_SETUP')
    python_version_path = setup_path + '/panel/data/python_version.pl'
    if os.path.exists(python_version_path):
        try:
            if os.path.getsize(python_version_path) == 0:
                os.remove(python_version_path)
            if os.path.exists(python_version_path):
                try:
                    with open(python_version_path, 'r') as f:
                        data = json.loads(f.read())
                except:
                    data = {}
            if time.time() - data['time'] < 2592000:
                version = data['version']
        except:
            pass
    else:
        try:
            res = public.httpGet(url)
        except:
            pass
        if res != None and res != '':
            try:
                version = res
                data = {'time': time.time(), 'version': version}
                with open(python_version_path, 'w') as f:
                    f.write(json.dumps(data))
                shell = '''"C:/Program Files/python/python.exe" -m pip install --upgrade pip'''
                # 开始尝试升级pip
                try:
                    os.system(shell)
                except:
                    pass
            except:
                pass
    version = version.strip()
    now_version = '{}.{}.{}'.format(sys.version_info[0], sys.version_info[1], sys.version_info[2])
    if version == now_version:
        # print('当前Python版本为：{}'.format(now_version))
        return
    panel_verison = panelPath + '/data/panel.version'
    if not os.path.exists(panel_verison):
        return
    with open(panel_verison, 'r') as f:
        panel_verison = f.read().strip()
    if int(panel_verison.split('.')[0]) >= 8:
        version1, version2, version3 = version.split('.')
        now_version1, now_version2, now_version3 = now_version.split('.')
        if int(version1) > int(now_version1):
            print('\n!!!!!!!!!!!!!!! \n检测到安装的python版本与面板要求的版本不一致，可能会导致面板异常 \n请前往 www.bt.cn 官网下载安并重新覆盖安装 \n!!!!!!!!!!!!!!!')
            os._exit(0)
        elif int(version1) == int(now_version1):
            if int(version2) > int(now_version2):
                # 需要提示升级
                print('\n!!!!!!!!!!!!!!! \n检测到安装的python版本与面板要求的版本不一致，可能会导致面板异常 \n请前往 www.bt.cn 官网下载并重新覆盖安装 \n!!!!!!!!!!!!!!!')
                os._exit(0)
            elif int(version2) == int(now_version2):
                if int(version3) > int(now_version3):
                    print('\n!!!!!!!!!!!!!!! \n检测到安装的python版本与面板要求的版本不一致，可能会导致面板异常 \n请前往 www.bt.cn 官网下载并重新覆盖安装 \n!!!!!!!!!!!!!!!')
                    os._exit(0)


def bt_cli(u_input=0):
    """
    命令行菜单
    """
    raw_tip = "==============================================="
    if not u_input:
        print("===============宝塔面板命令行==================")
        print("(1)  重启面板服务           (8)  改面板端口")
        print("(2)  停止面板服务           (9)  清除面板缓存")
        print("(3)  启动面板服务           (10) 清除登录限制")
        print("(4)  重载面板服务           (11) 设置是否开启IP + User-Agent验证")
        print("(5)  修改面板密码           (12) 取消域名绑定限制")
        print("(6)  修改面板用户名         (13) 取消IP访问限制")
        print("(7)  强制修改MySQL密码      (14) 查看面板默认信息")
        print("(22) 显示面板错误日志       (15) 清理系统垃圾")
        print("(23) 关闭BasicAuth认证      (16) 修复面板程序")
        print("(24) 关闭Google身份认证     (17) 升级到最新正式版")
        print("(25) 命令行启动面板         (27) 开启/关闭IPv6访问 ")
        print("(28) 关闭面板SSL功能        (29) 关闭面板访问设备认证 ")
        print("(0)  取消                   (0)  取消 ")
        print(raw_tip)

        try:
            check_python_version()
        except:
            pass
        try:
            u_input = input("请输入命令编号：")
            if sys.version_info[0] == 3: u_input = int(u_input)
        except:
            u_input = 0
    nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 22, 23, 24, 25, 66, 65, 27, 28, 29,68]
    if not u_input in nums:
        print(raw_tip)
        print("已取消!")
        exit()

    print(raw_tip)
    print("正在执行(%s)..." % u_input)
    print(raw_tip)

    if u_input == 1:
        os.system("bt restart")
    elif u_input == 2:
        os.system("bt stop")
    elif u_input == 3:
        os.system("bt start")
    elif u_input == 4:
        os.system("bt restart")
    elif u_input == 5:
        if sys.version_info[0] == 2:
            input_pwd = raw_input("请输入新的面板密码：")
        else:
            input_pwd = input("请输入新的面板密码：")
        set_panel_pwd(input_pwd.strip(), True)
    elif u_input == 6:
        if sys.version_info[0] == 2:
            input_user = raw_input("请输入新的面板用户名(>5位)：")
        else:
            input_user = input("请输入新的面板用户名(>5位)：")
        set_panel_username(input_user.strip())
    elif u_input == 7:
        if sys.version_info[0] == 2:
            input_mysql = raw_input("请输入新的MySQL密码：")
        else:
            input_mysql = input("请输入新的MySQL密码：")
        if not input_mysql:
            print("|-错误，不能设置空密码")
            return;

        if len(input_mysql) < 8:
            print("|-错误，长度不能少于8位")
            return;

        import re
        rep = "^[\w@\._]+$"
        if not re.match(rep, input_mysql):
            print("|-错误，密码中不能包含特殊符号")
            return;

        print(input_mysql)
        set_mysql_root(input_mysql.strip())
    elif u_input == 8:
        input_port = input("请输入新的面板端口：")
        if sys.version_info[0] == 3: input_port = int(input_port)
        if not input_port:
            print("|-错误，未输入任何有效端口")
            return;
        if input_port in [80, 443, 21, 20, 22, 3389, 3306]:
            print("|-错误，请不要使用常用端口作为面板端口")
            return;
        old_port = int(public.readFile('data/port.pl'))
        if old_port == input_port:
            print("|-错误，与面板当前端口一致，无需修改")
            return;
        is_exists = public.ExecShell("netstat -aon|findstr '%s'" % input_port)
        if len(is_exists[0]) > 5:
            print("|-错误，指定端口已被其它应用占用")
            return;

        set_panel_port(input_port)

        print("|-已将面板端口修改为：%s" % input_port)
        print("|-若您的服务器提供商是[阿里云][腾讯云][华为云]或其它开启了[安全组]的服务器,请在安全组放行[%s]端口才能访问面板" % input_port)
    elif u_input == 9:
        sess_file = 'data/session.db'
        if os.path.exists(sess_file): os.remove(sess_file)
        os.system("bt reload")
    elif u_input == 10:
        os.system("bt reload")
    elif u_input == 11:
        # auth_file = 'data/admin_path.pl'
        # if os.path.exists(auth_file): os.remove(auth_file)
        # os.system("bt reload")
        # print("|-已取消入口限制")
        not_tip = '{}/data/not_check_ip.pl'.format(public.get_panel_path())
        if os.path.exists(not_tip):
            os.remove(not_tip)
            print("|-已开启IP + User-Agent检测")
            print("|-此功能可以有效防止[重放攻击]")
        else:
            public.writeFile(not_tip, 'True')
            print("|-已关闭IP + User-Agent检测")
            print("|-注意：关闭此功能有被[重放攻击]的风险")

    elif u_input == 12:
        auth_file = 'data/domain.conf'
        if os.path.exists(auth_file): os.remove(auth_file)
        os.system("bt reload")
        print("|-已取消域名访问限制")
    elif u_input == 13:
        auth_file = 'data/limitip.conf'
        if os.path.exists(auth_file): os.remove(auth_file)
        os.system("bt reload")
        print("|-已取消IP访问限制")
    elif u_input == 14:
        local_ip = public.GetLocalIp()
        iplist_file_path = "{}/data/iplist.txt".format(panelPath)
        if not os.path.exists(iplist_file_path):
            with open(iplist_file_path, 'w') as f:
                f.write(local_ip)
        os.system("bt default")
    elif u_input == 15:
        ClearSystem()
    elif u_input == 16:
        RepPanel()
    elif u_input == 17:
        update_to()
    elif u_input == 22:
        if os.path.exists('%s/data/panelError.log' % panelPath):
            result = public.GetNumLines('%s/data/panelError.log' % panelPath, 100)
            print(result)
        else:
            print('暂无日志!')
    elif u_input == 23:
        filename = 'config/basic_auth.json'
        if os.path.exists(filename): os.remove(filename)
        os.system('bt reload')
        print("|-已关闭BasicAuth认证")
    elif u_input == 24:
        filename = 'data/two_step_auth.txt'
        if os.path.exists(filename): os.remove(filename)
        print("|-已关闭Google身份认证")
    elif u_input == 25:
        os.system('"C:\Program Files\python\python.exe" %s/runserver.py' % os.getenv('BT_PANEL'))
    elif u_input == 27:
        filename = 'data/ipv6.pl'
        if os.path.exists(filename):
            os.remove(filename)
            print("|-已关闭面板IPv6访问")
        else:
            public.writeFile(filename, 'True')
            print("|-已开启面板Ipv6访问")
        os.system('bt reload')
    elif u_input == 28:
        filename = 'data/ssl.pl'
        if os.path.exists(filename):
            os.remove(filename)
            print("|-已关闭面板SSL功能")
        os.system('bt reload')
    elif u_input == 29:
        filename = 'data/ssl_verify.pl'
        if os.path.exists(filename):
            os.remove(filename)
            print("|-已关闭面板双向认证")
        os.system('bt reload')
    elif u_input == 65:
        filename = 'data/debug.pl'
        if os.path.exists(filename):
            os.remove(filename)
            print('debug:off')
            os.system('net start btPanel')
            os.system('net start btTask')
        else:
            os.system('net stop btPanel')
            public.writeFile(filename, ' ')
            print('debug:on')
            os.system('"C:\Program Files\python\python.exe" %s/runserver.py' % os.getenv('BT_PANEL'))
    elif u_input == 66:
        input_version = input("请输入需要更新的版本：")
        if not input_version:
            print("|-错误，未输入任何有效版本")
            return;
        import panel_update
        update = panel_update.panel_update()
        ret = update.UpdatePanel(input_version)
        print('|-' + ret['msg'])
        if ret['status']:
            print("|-升级成功，正在重启面板")
            public.ExecShell('bt restart')

    elif u_input == 68:
        input_version = input("是否需要切换新版面板?y=切换新版,n=退回旧版 (y/n)：")
        if not input_version:
            print("|-错误，未输入任何有内容")
            return

        os.system("sc stop btPanel")
        os.system("sc delete btPanel")

        panel_path = public.get_panel_path()
        py_path = 'C:/Program Files/python/python.exe'
        if input_version == 'y':

            #拆分数据库
            os.system('"{}" {}/script/init_db.py repair'.format(py_path,panel_path))

            s_file = '{}/btPanel.exe'.format(panel_path)
            os.system('{} --services install'.format(s_file))
            os.system('{} --task install'.format(s_file))

            print("|-已设置为切换新版面板")
        else:
            public.ExecShell("\"{}\" {}/runserver.py --startup auto install".format(py_path,panel_path))
            public.ExecShell("\"{}\" {}/task.py --startup auto install".format(py_path,panel_path))
            print("|-已取消切换新版面板")

        os.system("sc start btPanel")

def package():
    try:
        o_str = input("请输入idc编号：")
        o_str = o_str.strip()
        panel_path = public.get_panel_path()
        # 写入 o.pl 文件
        if o_str:
            o_path = '{}/data/o.pl'.format(panelPath)
            res = public.writeFile(o_path, o_str)
            if not res:
                try:
                    os.remove(o_path)
                except:
                    pass
                public.writeFile(o_path, o_str)
        # 删除first.setup文件
        if os.path.exists('{}/data/first.setup'.format(panel_path)):
            try:
                os.remove('{}/data/first.setup'.format(panel_path))
            except:
                pass
        # 删除iplist.txt文件
        if os.path.exists('{}/data/iplist.txt'.format(panel_path)):
            try:
                os.remove('{}/data/iplist.txt'.format(panel_path))
            except:
                pass
        pass
        # 获取oem,名称
        try:
            oem_name = public.get_oem_name()
        except:
            oem_name = ''
        # 构造请求官网的url
        url = "https://www.bt.cn/Api/SetupCount?type=Windows&o={}".format(oem_name)
        # 请求官网
        try:
            public.httpGet(url, timeout=10)
        except:
            pass
        # 创建first_init.pl文件
        first_init_path = '{}/data/first_init.pl'.format(panel_path)
        public.writeFile(first_init_path, '')
    except:
        print(traceback.format_exc())

def set_panel_path(adminpath):
    admin_path = adminpath
    msg = ''
    from BTPanel import admin_path_checks
    if len(admin_path) < 6: msg = '安全入口地址长度不能小于6位!'
    if admin_path in admin_path_checks: msg = '该入口已被面板占用,请使用其它入口!'
    if not public.path_safe_check(admin_path) or admin_path[-1] == '.': msg = '入口地址格式不正确,示例: /my_panel'
    if admin_path[0] != '/':
        admin_path = "/" + admin_path
    admin_path_file = 'data/admin_path.pl'
    admin_path1 = '/'
    if os.path.exists(admin_path_file): admin_path1 = public.readFile(admin_path_file).strip()
    if msg != '':
        print('设置出错:{}'.format(msg))
        return
    public.writeFile(admin_path_file, admin_path)
    public.restart_panel()
    print('安全入口设置成功：{}'.format(admin_path))

def set_panel_ssl():
    pass

def get_temp_login():
    s_time = int(time.time())
    expire_time=int(int(time.time()) + 3600 * 3)
    public.M('temp_login').where('state=? and expire>?', (0, s_time)).delete()
    token = public.GetRandomString(48)
    salt = public.GetRandomString(12)

    pdata = {
        'token': public.md5(token + salt),
        'salt': salt,
        'state': 0,
        'login_time': 0,
        'login_addr': '',
        'expire': expire_time,
    }

    if not public.M('temp_login').count():
        pdata['id'] = 101

    if public.M('temp_login').insert(pdata):
        data_path = "{panel_path}/data/".format(
            panel_path = panelPath
        )
        if os.path.exists(data_path + 'ssl.pl'):
            HTTP_C="https://"
        else:
            HTTP_C="http://"

        IP_ADDRES=public.ExecShell("curl -sS --connect-timeout 10 -m 20 https://www.bt.cn/Api/getIpAddress")[0]

        PANEL_PORT=public.readFile(data_path + 'port.pl')

        PANEL_ADDRESS=HTTP_C+IP_ADDRES+":"+PANEL_PORT+"/login?tmp_token="+token
        print(PANEL_ADDRESS)

def get_panel_version() -> str:
    print(public.version())


if __name__ == "__main__":

    type = sys.argv[1]

    if type == 'root':
        set_mysql_root(sys.argv[2])
    elif type == 'panel':
        set_panel_pwd(sys.argv[2])
    elif type == 'username':
        if len(sys.argv) > 2:
            set_panel_username(sys.argv[2])
        else:
            set_panel_username()
    elif type == 'clear':
        ClearSystem()
    elif type == 'update_to':
        update_to()
    elif type == 're_panel':
        RepPanel()
    elif type == "cli":
        clinum = 0
        if len(sys.argv) > 2: clinum = int(sys.argv[2])
        bt_cli(clinum)
    elif type == "default":
        clinum = 14
        bt_cli(clinum)
    elif type == "get_config":
        get_panel_config(True)
    elif type == "get_panel_config":
        get_panel_config(False)
    elif type == "default_dir":
        set_panel_default_dir()
    elif type == "set_panel_port":
        set_panel_port(sys.argv[2])
    elif type == "unzip":
        set_unzip(sys.argv[2], sys.argv[3])
    elif type == "auto_update_panel":
        auto_update_panel()
    elif type == "get_cron_day":
        print('date: ' + public.format_date() + ' Successful')
    elif type == 'package':
        package()
    elif type == 'set_panel_path':
        param1 = sys.argv[2] if len(sys.argv) > 2 else ''
        set_panel_path(param1)
    elif type == 'set_panel_ssl':
        ...
    elif type == 'get_temp_login':
        get_temp_login()
    elif type == 'get_panel_version':
        get_panel_version()
    else:
        print('ERROR: Parameter error')
