蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

比较设置脚本和任务进程能读取的值

PYTHONWindows、Python 3.12.14、本机 Git for Windows Bash。练习无需账号。cloud_concepts_lab.py
cloud_concepts_lab.py79 行
"""Verify shell-session scope and an exact-host policy with wholly local sample data."""
from hashlib import sha256
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
from urllib.parse import urlsplit


SETUP = """export MB_SKY_SETUP_ONLY=prepared-in-shell
printf '%s\\n' "$MB_SKY_SETUP_ONLY" "$MB_SKY_SHARED_SETTING" > setup-result.txt
printf '%s\\n' "prepared artifact" > setup-artifact.txt
"""
TASK = """printf '%s\\n' "${MB_SKY_SETUP_ONLY:-absent}" "$MB_SKY_SHARED_SETTING"
cat setup-artifact.txt
"""


def allowed_example(method, url):
    parts = urlsplit(url)
    return (method in {"GET", "HEAD", "OPTIONS"} and parts.scheme == "https"
            and parts.hostname == "packages.example.invalid" and parts.port in {None, 443}
            and parts.username is None and parts.password is None)


def main():
    if os.name == "nt":
        git = shutil.which("git.exe")
        bash = Path(git).resolve().parents[1] / "bin/bash.exe" if git else Path("bash.exe")
        if not bash.is_file():
            raise SystemExit("Git for Windows Bash is required.")
    else:
        bash = Path(shutil.which("bash") or "bash")
        if not bash.is_file():
            raise SystemExit("GNU Bash is required.")

    env = {key: val for key, val in os.environ.items() if key not in {"BASH_ENV", "ENV", "MB_SKY_SETUP_ONLY"}}
    env["MB_SKY_SHARED_SETTING"] = "configured-value"

    def shell(*args, cwd=None):
        result = subprocess.run([bash, "--noprofile", "--norc", *args], env=env, cwd=cwd, check=True,
                                capture_output=True, encoding="utf-8", timeout=20)
        return result.stdout

    cases = []

    def check(name, data, operation, expected, actual):
        assert expected == actual, (name, expected, actual)
        cases.append(dict(name="cloud_" + name, input=data, operation=operation, expected=expected, actual=actual))

    with TemporaryDirectory(prefix="mbsky-cloud-shell-") as temporary:
        root = Path(temporary)
        shell("-c", SETUP, cwd=root)
        observed_setup = (root / "setup-result.txt").read_text(encoding="utf-8").splitlines()
        check("setup", SETUP, "Execute an independent setup shell with MB_SKY_SHARED_SETTING=configured-value",
              ["prepared-in-shell", "configured-value"], observed_setup)
        check("task", TASK, "Execute another shell with the original environment and same work directory",
              ["absent", "configured-value", "prepared artifact"], shell("-c", TASK, cwd=root).splitlines())

    cases_to_try = [
        ("GET","https://packages.example.invalid/archive", True),
        ("POST","https://packages.example.invalid/archive", False),
        ("GET","https://packages.example.invalid.evil.invalid/archive", False),
        ("GET","http://packages.example.invalid/archive", False),
    ]
    for label, (method, url, expected) in zip(("get","post","suffix","http"),cases_to_try,strict=True):
        check("policy_"+label, [method, url], "Evaluate the authored network-policy example locally",
              expected, allowed_example(method, url))

    print(json.dumps(dict(version={"python":sys.version.split()[0],"bash":shell("--version").splitlines()[0]},
                          bash_sha256=sha256(bash.read_bytes()).hexdigest(), cases=cases)))


if __name__ == "__main__":
    main()
本例需在 Windows、Python 3.12.14、本机 Git for Windows Bash。练习无需账号。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Python 3.12.14、本机 Git for Windows Bash。练习无需账号。

入口文件:projects/codex-cloud_concepts/cloud_concepts_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 cloud_concepts_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Python 3.12.14、本机 Git for Windows Bash。练习无需账号。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Codex 教程

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a99.zip

下载课程关联工程包:Codex 教程

课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a90.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习