Esempio n. 1
0
def on_task_exception(self):
    logger.exception("An internal error occurred in the application")
    toast_msg = ("应用发生内部错误" if "zh" in session_info.user_language else
                 "An internal error occurred in the application")

    e_type, e_value, e_tb = sys.exc_info()
    lines = traceback.format_exception(e_type, e_value, e_tb)
    traceback_msg = "".join(lines)

    traceback_console = Console(color_system="truecolor",
                                tab_size=2,
                                record=True,
                                width=90)
    with traceback_console.capture():  # prevent logging to stdout again
        traceback_console.print_exception(word_wrap=True,
                                          extra_lines=1,
                                          show_locals=True)

    if State.theme == "dark":
        theme = DARK_TERMINAL_THEME
    else:
        theme = LIGHT_TERMINAL_THEME

    html = traceback_console.export_html(theme=theme,
                                         code_format=TRACEBACK_CODE_FORMAT,
                                         inline_styles=True)
    try:
        popup(title=toast_msg, content=put_html(html), size=PopupSize.LARGE)
        run_js(
            "console.error(traceback_msg)",
            traceback_msg="Internal Server Error\n" + traceback_msg,
        )
    except Exception:
        pass
Esempio n. 2
0
 def __get_disk():
     disk_num = pywebio.input.input("请输入虚拟磁盘的个数",
                                    type=pywebio.input.NUMBER,
                                    value=1)
     disks = ""
     for i in range(disk_num):
         disk_info = dict(
             pywebio.input.input_group(
                 "虚拟磁盘{}信息".format(i + 1),
                 [
                     pywebio.input.input("虚拟机磁盘镜像的绝对路径", name="disk_path"),
                     pywebio.input.select(
                         "虚拟磁盘镜像格式",
                         [
                             ("RAW(IMG, ISO)", "raw"),
                             ("QCOW", "qcow"),
                             ("VHD(Windows)", "vhd"),
                         ],
                         name="disk_format",
                     ),
                 ],
             ))
         try:
             if not disk_info["disk_path"]:
                 popup("磁盘路径为空!")
             else:
                 disks += " -drive file={},if=virtio,format={},id=drive-virtio-disk{} ".format(
                     os.path.abspath(disk_info["disk_path"]),
                     disk_info["disk_format"],
                     i,
                 )
         except KeyError:
             popup("输入出错!")
     return disks
Esempio n. 3
0
def main():
    set_env(title="FlyOS Panel", auto_scroll_bottom=True)
    put_html("<h1>FlyOS WEB Panel</h1>")
    put_text('FlyOS Panel By:XingYuJie', sep=' ')
    popup(
        '欢迎使用FlyOS Panel!', '欢迎使用FlyOS WEB Panel!'
        '如果程序有Bug,'
        '请务必提交到邮箱:[email protected]谢谢!'
        '程序由MicroTech Projects -- FlyOS强力驱动')
    put_link("web终端", url=f'http://{get_host_ip()}:7681')
    put_text('_______________________', sep=' ')
    put_link("VM虚拟机", url=f'http://{get_host_ip()}:8002')
    put_text('_______________________', sep=' ')
    put_link("vscode", url=f'http://{get_host_ip()}:2001')
    put_text('_______________________', sep=' ')
    put_link("Apache主页", url=f'http://{get_host_ip()}:8080')
    put_text('_______________________', sep=' ')
    put_link("Nginx主页", url=f'http://{get_host_ip()}:8088')
    put_text('_______________________', sep=' ')
    put_link("HTTP文件服务器", url=f'http://{get_host_ip()}:8081')
    put_text('_______________________', sep=' ')
    put_link("jupyter notebook", url=f'http://{get_host_ip()}:2000')
    put_text('_______________________', sep=' ')
    put_link("FlyOS桌面环境", url=f'http://{get_host_ip()}:6081/vnc.html')
    put_text('_________系统工具__________', sep=' ')
    put_link("FlyOS AM调用 ", url=f'http://{get_host_ip()}:5000')
    put_text('_______________________', sep=' ')
    put_link("FlyOS Termux:API调用 ", url=f'http://{get_host_ip()}:5002')
Esempio n. 4
0
def main():
    set_env(title="FlyOS Panel",
            auto_scroll_bottom=True
        )
    put_html("<h1>FlyOS WEB Panel</h1>")
    put_text('FlyOS Panel By:XingYuJie',
            sep=' '
        )
    popup('欢迎使用FlyOS Panel!',
            '欢迎使用FlyOS WEB Panel!'
            '如果程序有Bug,'
            '请务必提交到邮箱:[email protected]谢谢!'
            '程序由MicroTech Projects -- FlyOS强力驱动'
        )
    put_link("本地WEB终端",
            url='http://127.0.0.1:4200'
        )
    put_text('_______________________',
            sep=' '
        )
    put_link("VM虚拟机",
            url='http://127.0.0.1:8002'
        )
    put_text('_______________________',
            sep=' '
        )
    put_link("Apache主页",
            url='http://127.0.0.1:8080'
        )
    put_text('_______________________',
            sep=' '
        )
    put_link("Nginx主页",
            url='http://127.0.0.1:8088'
        )
    put_text('_______________________',
            sep=' '
        )
    put_link("HTTP文件服务器",
            url='http://127.0.0.1:8081'
        )
    put_text('_______________________',
            sep=' '
        )
    put_link("FlyOS RunShell Tool",
            url='http://127.0.0.1:8887'
        )
    put_text('_________系统工具__________',
            sep=' '
        )
    put_link("FlyOS AM调用 ",
            url='http://127.0.0.1:5000'
        )
    put_text('_______________________',
            sep=' '
        )
    put_link("FlyOS Termux:API调用 ",
            url='http://127.0.0.1:5002'
            )
Esempio n. 5
0
 async def join(self):
     """进入 Linux 系统"""
     options = []
     dirs = os.listdir("{}/cmd".format(self.path))
     for vm_path in dirs:
         options.append((vm_path, vm_path))
     linux = pywebio.input.select("选择创建的Linux名称", options=options)
     popup('打开Linux', '请在终端输入 `$FLYOS/deploylinux/cmd/{}` 打开 Linux'.format(linux))
Esempio n. 6
0
    def create(self):
        """
        创建虚拟机函数,返回虚拟机运行命令
        """
        command = pywebio.input.select(
            label="请选择qemu的命令",
            options=[
                ("qemu-system-i386 (x86)", "qemu-system-i386 "),
                ("qemu-system-x86_64 (amd64)", "qemu-system-x86_64 "),
                ("qemu-system-arm (arm32)", "qemu-system-arm"),
                ("qemu-system-aarch64 (arm64)", "qemu-system-aarch64 "),
            ],
        )
        cdrom = self.__get_cdrom()
        disk = self.__get_disk()

        memory = pywebio.input.input(
            "请输入虚拟机内存(不建议太大),Windows 95/98建议512以下,NT/XP建议768,Windows7/8建议1G左右 :"
        )
        network = pywebio.input.input("请输入网卡型号(建议rtl8139):")
        vnc = pywebio.input.input("输入VNC端口号(建议0):")
        vga = pywebio.input.input("显卡型号,NT系建议vmware,Windowz95/98建议cirrus:")
        extra = pywebio.input.input("额外参数,没有留空:")
        # 判断是否有额外参数,否则添加
        if not extra:
            extra = ""
        else:
            extra = " " + extra

        # 判断是否有网卡,否则提供默认
        if not network:
            network = "rtl8139"

        # 判断是否自定义内存大小,否则使用默认128
        if not memory:
            memory = "128"

        # 判断是否有显卡类型,否则使用默认的vmware
        if not vga:
            vga = "vmware"

        # 判断是否有自定义vnc端口,否则使用默认的0
        if not vnc:
            vnc = "0"

        memory = " -m " + memory
        network = " -net user -net nic,model=" + network
        vga = " -vga " + vga
        vnc = " -vnc :" + vnc
        result = (command + cdrom + disk + memory + network + vga + vnc +
                  extra)
        popup("确认配置: " "要执行的命令" f"{result}")
        print(result)

        return result
Esempio n. 7
0
def main():
    set_env(title="Linux  部署程序--中文版", auto_scroll_bottom=True)
    put_html("<h1>FlyOS Linux Deploy</h1>")
    put_text("By:FlyOS MicroTech XingYuJie(严禁删除版权,不允许修改版权)GPL-V3", sep=" ")
    popup(
        "欢迎使用Linux部署程序--中文版",
        "欢迎使用Linux部署程序--中文版。"
        "开始部署你的Linux吧!"
        "程序由MicroTech Projects -- FlyOS强力驱动",
    )
    Main()
Esempio n. 8
0
def get_rootfs(rootfs_url, name, ext, command):
    popup("正在下载rootfs……")
    with open("{}/rootfs/{}.tar.{}".format(path, name, ext), "wb") as f:
        r = requests.get(rootfs_url, timeout=600, verify=False, stream=True)
        f.write(r.content)

    popup("正在解压rootfs……")
    ta_path = "rootfs/{}".format(name)
    fs = tarfile.open("{path}/rootfs/{name}.tar.{ext}".format(
        path=path, name=name, ext=ext))  # 打开压缩文件
    for i in fs.getmembers():
        fs.extract(i, path=path)  # 解压所有文件至rootfs目录
    # get_result(
    #     'tar x{type}vf rootfs/{name}.tar.{ext} -C rootfs/{name}'.format(type='J' if ext == 'xz' else 'gz',
    #                                                                     )
    popup("正在清理……")
    os.system("rm -f {}/rootfs/{}.tar.{}".format(path, name, ext))
    popup("正在创建配置……")
    conf_template = """
    if [ -z $1 ]; then
        {command} rootfs/{name}/ /bin/bash
    else
    {command} rootfs/{name}/ /bin/sh -c $1
    fi
    """
    with open("cmd/{name}".format(name=name), "w") as f:
        f.write(conf_template.format(command=command, name=name))
    os.system("chmod +x cmd/{name}".format(name=name))
Esempio n. 9
0
def main():
    """主方法"""
    if not os.path.exists(FLYOS_ROOT + "/.firstuse/lock"):
        set_env(title="欢迎使用FlyOS", auto_scroll_bottom=True)
        put_html("<h1>欢迎使用! -- FlyOS 初始化向导</h1>")
        put_text('欢迎使用FlyOS!开始初始化您的FlyOS吧!')
        popup('Hi,There!欢迎使用FlyOS!让我们来初始化FlyOS吧!')

        password = pywebio.input.input("设置您的系统密码:", type="password")
        vpwd = pywebio.input.input("请再次输入密码验证:", type="password")
        if password != vpwd:
            popup('错误', "两次输入密码不一致,请刷新页面重试")
            return
        put_text('初始化完成!请进入termuxAPP开始体验FlyOS吧!')
        termux_auth.change_passwd(password)
        os.mkdir(f"{HOME}/.flyos")
    os.kill(os.getpid(), 9)
Esempio n. 10
0
def main():
    set_env(title="Linux  部署程序--中文版", auto_scroll_bottom=True)
    put_html("<h1>FlyOS Linux Deploy</h1>")
    put_text("By:FlyOS MicroTech XingYuJie(严禁删除版权,不允许修改版权)GPL-V3", sep=" ")
    popup(
        "欢迎使用Linux部署程序--中文版",
        "欢迎使用Linux部署程序--中文版。"
        "开始部署你的Linux吧!"
        "程序由MicroTech Projects -- FlyOS强力驱动",
    )
    n = pywebio.input.select(
        "请选择你要执行的操作",
        options=[
            ("安装Linux", 1, True),
            ("进入Linux", 2),
        ],
    )
    if n == 1:
        name = pywebio.input.input("请输入该系统的名字")
        command = pywebio.input.radio(
            "请选择要用的命令",
            [
                ("PRoot(无root下使用)", "proot -r ", True),
                ("chroot(有root建议使用)", "sudo chroot "),
            ],
        )
        arch = subprocess.getoutput("dpkg --print-architecture")
        num = pywebio.input.select(
            "请选择你要安装的系统",
            options=[
                ("Ubuntu", 1, True),
                ("CentOS", 2),
                ("Kali", 3),
            ],
        )
        if num == 1:
            get_ubuntu(name, arch, command)
        elif num == 2:
            get_centos(name, arch, command)
        elif num == 3:
            get_kali(name, arch, command)
    elif n == 2:
        join()
    elif n == 3:
        delete()
Esempio n. 11
0
def main():
    set_env(title="FlyOS Virtual Machine", auto_scroll_bottom=True)
    put_html("<h1>FlyOS WEB Virtual Machine</h1>")
    put_text('FlyOS Virtual Machine By:XingYuJie', sep=' ')
    popup(
        '欢迎使用FlyOS FlyOS Virtual Machine!', '欢迎使用FlyOS Virtual Machine。'
        '开始创建您的虚拟机吧!'
        '程序由MicroTech Projects -- FlyOS强力驱动')
    cpu = pywebio.input.input("请输入架构,例如i386架构:")
    path = pywebio.input.input("请输入虚拟机磁盘镜像完整绝对路径:")
    memory = pywebio.input.input("请输入虚拟机内存(不建议太大):")
    network = pywebio.input.input("请输入网卡驱动(建议rtl8139):")
    vga = pywebio.input.input("请输入显卡驱动(建议vmware):")
    vnc = pywebio.input.input("输入VNC端口号(建议0):")
    qemu = f"qemu-system-{cpu} "
    qemu += f"-hda {path} -m {memory} -device {network} "
    qemu += f"-vga {vga} -vnc :{vnc}"
    os.system(qemu)
Esempio n. 12
0
 async def get_result(cmd):
     """
     params:
         cmd - 要执行的命令
     """
     if re.search('[;&|<>$]', cmd):
         popup('检测到非法字符', content="请检查命令中是否包含;&|等特殊字符, 并刷新重试")
         return
     popen = subprocess.Popen(cmd,
                              shell=True,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.STDOUT,
                              text=True)
     while True:
         buff = popen.stdout.readline()
         if buff:
             put_text(buff)
         elif popen.poll() is not None:
             break
Esempio n. 13
0
 def __get_cdrom():
     cdrom_num = pywebio.input.input("请输入虚拟光盘的个数",
                                     type=pywebio.input.NUMBER,
                                     value=1)
     cdroms = ""
     for i in range(cdrom_num):
         cdrom_info = dict(
             pywebio.input.input_group("光盘{}信息".format(i + 1), [
                 pywebio.input.input("虚拟机光盘镜像的绝对路径", name="cdrom_path"),
             ]))
         try:
             if not cdrom_info["cdrom_path"]:
                 popup("光盘路径为空!")
             else:
                 cdroms += " -cdrom {} ".format(
                     os.path.abspath(cdrom_info["disk_path"]))
         except KeyError:
             popup("输入出错!")
     return cdroms
Esempio n. 14
0
 def __init__(self):
     env = os.getenv('FLYOS')
     if env is None:
         env = '.'
     self.__path = os.path.abspath(env + '/virtualmachine')
     if not os.path.exists(os.path.abspath(self.__path + "/vms")):
         os.mkdir(os.path.abspath(self.__path + "/vms"))
     set_env(title="FlyOS Virtual Machine", auto_scroll_bottom=True)
     put_html("<h1>FlyOS WEB Virtual Machine</h1>")
     put_text("FlyOS Virtual Machine By:XingYuJie", sep=" ")
     popup(
         "欢迎使用FlyOS FlyOS Virtual Machine!",
         "欢迎使用FlyOS Virtual Machine。"
         "开始创建您的虚拟机吧!"
         "程序由MicroTech Projects -- FlyOS强力驱动",
     )
     pwd = pywebio.input.input("输入flyos密码:")
     if termux_auth.auth(pwd):
         self.__run()
     else:
         popup("密码错误,请刷新页面重试")
Esempio n. 15
0
def test_extractor(uex_data):
    # The signature according to https://pywebio.readthedocs.io/en/latest/input.html?highlight=actions#pywebio.input.input_group
    # only supports one invalid thing at a time.
    failures = list()

    with popup("Applying the example to the extractor"):
        try:
            if uex_data["name"] == DEFAULT_HOOK["name"]:
                put_text("You need to provide a unique name for this hook")
                failures.append(
                    ["name", "Name is not changed from the default"])
            if uex_data["path"] == DEFAULT_HOOK["path"]:
                put_text("You need to provide a unique path for this hook")
                failures.append([
                    "path",
                    "The path for the webhook is not changed from the default",
                ])
            if uex_data["queue_name"] == DEFAULT_HOOK["queue_name"]:
                put_text(
                    "You need to provide a unique queue_name for this hook")
                failures.append([
                    "queue_name",
                    "The queue_name for the webhook is not changed from the default",
                ])
            put_text(
                extractions.apply_extractor_to_message(uex_data["example"],
                                                       uex_data["extractor"]))
        except json.decoder.JSONDecodeError as e:
            put_text(
                f"The json didn't validate! The error returned is {str(e)}")
            failures.append(["example", "The example json didn't check out"])
        except (
                jmesex.IncompleteExpressionError,
                jmesex.EmptyExpressionError,
                jmesex.ParseError,
        ) as e:
            put_text(
                f"The jmespath expression didn't validate! The error returned is {str(e)}"
            )
            failures.append(
                ["extractor", "The jmespath expression didn't check out"])
    if failures:
        return (failures[0][0], failures[0][1])
    if uex_data["action"].lower() == "test":
        return ("actions", "test was run")
    return None
Esempio n. 16
0
    def ui_add_alas(self) -> None:
        with popup(t("Gui.AddAlas.PopupTitle")) as s:

            def get_unused_name():
                all_name = alas_instance()
                for i in range(2, 100):
                    if f"alas{i}" not in all_name:
                        return f"alas{i}"
                else:
                    return ""

            def add():
                name = pin["AddAlas_name"]
                origin = pin["AddAlas_copyfrom"]

                if name not in alas_instance():
                    r = read_file(filepath_config(origin))
                    write_file(filepath_config(name), r)
                    self.set_aside()
                    self.active_button("aside", self.alas_name)
                    close_popup()
                else:
                    clear(s)
                    put(name, origin)
                    put_error(t("Gui.AddAlas.FileExist"), scope=s)

            def put(name=None, origin=None):
                put_input(
                    name="AddAlas_name",
                    label=t("Gui.AddAlas.NewName"),
                    value=name or get_unused_name(),
                    scope=s,
                ),
                put_select(
                    name="AddAlas_copyfrom",
                    label=t("Gui.AddAlas.CopyFrom"),
                    options=["template"] + alas_instance(),
                    value=origin or "template",
                    scope=s,
                ),
                put_button(label=t("Gui.AddAlas.Confirm"),
                           onclick=add,
                           scope=s)

            put()
Esempio n. 17
0
 async def get_rootfs(rootfs_url, name, ext, command):
     popup('正在下载rootfs……')
     await get_result('wget {} -O rootfs/{}.tar.{}'.format(
         rootfs_url, name, ext))
     popup('正在解压rootfs……')
     await get_result(
         'tar x{type}vf rootfs/{name}.tar.{ext} -C rootfs/{name}'.format(type='J' if ext == 'xz' else 'gz',
                                                                         name=name, ext=ext))
     popup('正在清理……')
     await get_result('rm -f rootfs/{}.tar.{}'.format(name, ext))
     popup('正在创建配置……')
     conf_template = '''
     if [ -z $1 ]; then
         {command} rootfs/{name}/ /bin/bash
     else
     {command} rootfs/{name}/ /bin/sh -c $1
     fi
     '''
     await get_result(
         'echo {cmd} > cmd/{name} && chmod +x cmd/{name}'.format(
             cmd=conf_template.format(command=command, name=name), name=name))
Esempio n. 18
0
def main():
    set_env(title="FlyOS Devices API Tool", auto_scroll_bottom=True)
    put_html("<h1>FlyOS Devices API Tool</h1>")
    pwd = pywebio.input.input("输入flyos密码: ")
    if termux_auth.auth(pwd):
        while 1:
            api = pywebio.input.input("输入api调用接口:")
            if re.search('[;&|<>$]', api):
                popup('检测到非法字符', content="请检查命令中是否包含;&|等特殊字符")
                continue
            status, output = subprocess.getstatusoutput(f'termux-{api}')
            if status == 0:
                popup('命令已执行', output)
            else:
                popup('执行时出现错误', output)
    else:
        put_text("密码错误, 请刷新页面重试")
Esempio n. 19
0
def main():
    set_env(title="FlyOS Phone Shell", auto_scroll_bottom=True)
    put_html("<h1>FlyOS WEB Phone Shell</h1>")
    put_text('FlyOS Phone Web Shell By:XingYuJie', sep=' ')
    pwd = pywebio.input.input("输入flyos密码:")
    if termux_auth.auth(pwd):
        while 1:
            command = pywebio.input.input("请输入AM参数加命令:")
            if re.search('[;&|<>$]', command):
                popup('检测到非法字符', content="请检查命令中是否包含;&|等特殊字符")
                continue
            status, output = subprocess.getstatusoutput("am " + command)
            if status == 0:
                popup('命令已执行', output)
            else:
                popup('命令执行时出现错误', output)
    else:
        put_text("密码错误,请刷新页面重试")
Esempio n. 20
0
from sontop import SonTop, SonTopPC
from pywebio.output import popup

game1 = SonTop()
game1.play()
taxminUser = game1.getResult()

game2 = SonTopPC()
game2.play()
if game2.gameOver:
    taxminPC = game2.getResult()

if taxminUser < taxminPC:
    popup("Tabriklayman!", f"Siz {taxminUser} ta taxmin bilan yutdingiz!")
elif taxminUser > taxminPC:
    popup("G'alaba!", f"Men {taxminPC} ta taxmin bilan yutdim!")
else:
    popup("Durran", f"Ikkalamizda ham {taxminPC} ta taxmin.")
Esempio n. 21
0
def main():
    """主方法"""
    if not os.path.exists(FLYOS_ROOT + "/.firstuse/lock"):
        set_env(title="欢迎使用FlyOS", auto_scroll_bottom=True)
        put_html("<h1>欢迎使用! -- FlyOS 初始化向导</h1>")
        put_text('欢迎使用FlyOS!开始初始化您的FlyOS吧!')
        popup('Hi,There!欢迎使用FlyOS!让我们来初始化FlyOS吧!')
        password = pywebio.input.input("设置您的系统开机密码:", type="password")
        vpwd = pywebio.input.input("请再次输入密码验证:", type="password")
        if password != vpwd:
            popup('错误', "两次输入密码不一致,请刷新页面重试")
            return
        put_text('初始化完成!请进入termuxAPP开始体验FlyOS吧!')
        termux_auth.change_passwd(password)
    try:
        os.mkdir(f"{HOME}/.flyos")
    except FileExistsError:
        pass
    conn = sqlite3.connect(f'{HOME}/.flyos/service.db')
    cur = conn.cursor()
    cur.execute('''CREATE TABLE boot (
        ID INTEGER PRIMARY KEY NOT NULL,
        command           TEXT    NOT NULL,
        status            INT     NOT NULL
        );''')
    cur.execute('''CREATE TABLE login (
        ID INTEGER PRIMARY KEY NOT NULL,
        command           TEXT    NOT NULL,
        status            INT     NOT NULL
        );''')
    cur.execute('''INSERT INTO boot (command, status) VALUES (
        "ttyd pwlogin", 1
    )''')
    cur.execute(f'''INSERT INTO boot (command, status) VALUES (
        "python {FLYOS_ROOT}/panel/server.py", 1
    )''')
    cur.execute('''INSERT INTO boot (command, status) VALUES (
        "apachectl start", 1
    )''')
    cur.execute(f'''INSERT INTO boot (command, status) VALUES (
        "python {FLYOS_ROOT}/virtualmachine/web.py", 1
    )''')
    cur.execute('''INSERT INTO boot (command, status) VALUES (
        "nginx", 1
    )''')
    cur.execute('''INSERT INTO boot (command, status) VALUES (
        "php-fpm", 1
    )''')
    cur.execute('''INSERT INTO boot (command, status) VALUES (
        "http-server", 1
    )''')
    cur.execute(f'''INSERT INTO boot (command, status) VALUES (
        "python {FLYOS_ROOT}/phone/web.py", 1
    )''')
    cur.execute(f'''INSERT INTO boot (command, status) VALUES (
        "python {FLYOS_ROOT}/api/web.py", 1
    )''')
    cur.execute('''INSERT INTO boot (command, status) VALUES (
        "sshd", 1
    )''')
    cur.execute('''INSERT INTO boot (command, status) VALUES(
        "jupyter notebook --ip='0.0.0.0' --port=2000 --NotebookApp.token='' --no-browser", 1
    )''')
    cur.execute('''INSERT INTO boot (command, status) VALUES(
        "termux-wake-lock", 1
    )''')
    cur.execute('''INSERT INTO boot (command, status) VALUES(
        "code-server --bind-addr 0.0.0.0:2001", 1
    )''')
    conn.commit()
    conn.close()

    os.kill(os.getpid(), 9)
Esempio n. 22
0
def main():
    """主方法"""
    if not os.path.exists(FLYOS_ROOT + "/.firstuse/lock"):
        set_env(title="欢迎使用FlyOS", auto_scroll_bottom=True)
        put_html("<h1>欢迎使用! -- FlyOS 初始化向导</h1>")
        put_text('欢迎使用FlyOS!开始初始化您的FlyOS吧!')
        popup('Hi,There!欢迎使用FlyOS!让我们来初始化FlyOS吧!')
        password = pywebio.input.input("设置您的系统开机密码:", type="password")
        vpwd = pywebio.input.input("请再次输入密码验证:", type="password")
        if password != vpwd:
            popup('错误', "两次输入密码不一致,请刷新页面重试")
            return
        put_text('初始化完成!请进入termuxAPP开始体验FlyOS吧!')
        termux_auth.change_passwd(password)
    try:
        os.mkdir(f"{HOME}/.flyos")
    except FileExistsError:
        pass
    conn = sqlite3.connect(f'{HOME}/.flyos/service.db')
    cur = conn.cursor()
    cur.execute('''CREATE TABLE boot (
        ID INTEGER PRIMARY KEY NOT NULL,
        command           TEXT    NOT NULL,
        status            INT     NOT NULL
        );''')
    cur.execute('''CREATE TABLE login (
        ID INTEGER PRIMARY KEY NOT NULL,
        command           TEXT    NOT NULL,
        status            INT     NOT NULL
        );''')
    cur.execute('''INSERT INTO boot (command, status) VALUES (
        "shellinaboxd --disable-ssl --background", 1
    )''')
    cur.execute('''INSERT INTO boot (command, status) VALUES (
        "nohup python $FLYOS/panel/server.py &", 1
    )''')
    cur.execute('''INSERT INTO boot (command, status) VALUES (
        "nohup python $FLYOS/panel/shell.py &", 1
    )''')
    cur.execute('''INSERT INTO boot (command, status) VALUES (
        "apachectl start", 1
    )''')
    cur.execute('''INSERT INTO boot (command, status) VALUES (
        "nohup python $FLYOS/virtualmachine/web.py &", 1
    )''')
    cur.execute('''INSERT INTO boot (command, status) VALUES (
        "nohup nginx &", 1
    )''')
    cur.execute('''INSERT INTO boot (command, status) VALUES (
        "nohup php-fpm &", 1
    )''')
    cur.execute('''INSERT INTO boot (command, status) VALUES (
        "nohup http-server &", 1
    )''')
    cur.execute('''INSERT INTO boot (command, status) VALUES (
        "nohup python $FLYOS/phone/web.py &", 1
    )''')
    cur.execute('''INSERT INTO boot (command, status) VALUES (
        "nohup python $FLYOS/api/web.py &", 1
    )''')
    cur.execute('''INSERT INTO boot (command, status) VALUES (
        "sshd", 1
    )''')
    conn.commit()
    conn.close()

    os.kill(os.getpid(), 9)
Esempio n. 23
0
    def __run(self):
        num = pywebio.input.select(options=[
            ("运行虚拟机", 1, True),
            ("运行模板", 2, False),
            ("创建虚拟机", 3, False),
        ])
        if num == 1:
            run_type = pywebio.input.radio(options=[("新建临时",
                                                     "1"), ("运行已保存的配置文件",
                                                            "2")])
            if run_type == "1":
                qemu = self.create()
                asyncio.run(self.get_result(qemu))
                popup(
                    "恭喜,虚拟机成功创建,请在网上或应用市场下载vncviewer,打开+点击右下角,名称随便取,点击列表名称连接即可"
                )
            elif run_type == "2":
                options = []
                dirs = os.listdir("{}/vms".format(self.__path))
                for path in dirs:
                    options.append((path[:5], path[:5]))
                conf = pywebio.input.select("选择创建的虚拟机名称", options=options)
                os.environ["conf"] = str(conf)
                run = "bash {}/vms/$conf.conf".format(self.__path)
                asyncio.run(self.get_result(run))
                popup(
                    "恭喜,虚拟机成功运行,请在网上或应用市场下载vncviewer,打开+点击右下角,名称随便取,点击列表名称连接即可"
                )
        elif num == 2:
            print(
                "模板VNC端口都为:5900,没有图形将从串口输出,内存分配视Guest机系统而定,请确保有500MB左右的剩余储存空间")
            template_num = pywebio.input.select(options=[
                ("Windows", "1", True),
                ("SunOS", "2", False),
                ("HelenOS", "3", False),
            ])

            if template_num == "1":
                template_type = pywebio.input.radio(
                    options=[("Windows95", "1"), ("WindowsXP", "2")])

                os.environ["w"] = str(template_type)
                sh_name = "Windows"
                asyncio.run(
                    self.get_result("sh {}/templates/".format(self.__path) +
                                    sh_name + ".sh"))
                # cd $FLYOS/virtualmachine && sh 2.sh
                popup(
                    "恭喜,模板成功运行,请在网上或应用市场下载vncviewer,打开+点击右下角,名称随便取,点击列表名称连接即可")
            elif template_num == "2":
                template_type = pywebio.input.radio(
                    options=[("SunOS4.13", "1"), ("SunOS4.14",
                                                  "2"), ("Solaris2.4", "3")])
                os.environ["sp"] = str(template_type)
                sh_name = "3"
                asyncio.run(self.get_result("sh templates/" + sh_name + ".sh"))
                popup(
                    "恭喜,模板成功运行,请在网上或应用市场下载vncviewer,打开+点击右下角,名称随便取,点击列表名称连接即可")

            elif template_num == "3":
                archi = pywebio.input.radio(options=[("i386", "1"), ("arm",
                                                                     "2")])
                sh_name = "4"
                os.environ["h"] = str(archi)
                asyncio.run(
                    self.get_result("sh {}/templates/".format(self.__path) +
                                    sh_name + ".sh"))
                popup(
                    "恭喜,模板成功运行,请在网上或应用市场下载vncviewer,打开+点击右下角,名称随便取,点击列表名称连接即可")

        elif num == 3:
            qemu = self.create()
            name = pywebio.input.input("虚拟机名称:")
            os.environ["qemu"] = str(qemu)
            os.environ["vm"] = str(name)
            save = "echo $qemu; echo $vm; echo $qemu > %s/vms/${vm}.conf " % self.__path
            asyncio.run(self.get_result(save))
            popup("恭喜,虚拟机成功保存,请在网上或应用市场下载vncviewer,打开+点击右下角,名称随便取,点击列表名称连接即可")
Esempio n. 24
0
from pywebio import input, output
from time import *

output.put_markdown("## Hi </fooders>")
output.put_markdown("<p>I am Jayant</p>")

output.put_table([["Name", "code"], ['Food', 11], ['Water', 12],
                  ['Sunlight', 13]])

with output.popup("Subscribe to the page"):
    output.put_text("Join Other Customer!")

food = input.select("Choose Your Favorite Food", ['Maggi', 'Noodles'])
output.put_text("You Choose", food, "from given list")

output.put_processbar('bar')

for i in range(1, 11):
    output.set_processbar('bar', i / 10)
    sleep(0.1)

output.put_markdown("Your Order is ready")

if food == "Maggi":
    with open("maggi.jpg", "rb+") as f:
        image = f.read()
else:
    with open("noodles.jpg", "rb+") as f:
        image = f.read()

output.put_image(image, height="100", width="100")