github.com/igoogolx/clash@v1.19.8/docs/zh_CN/premium/script.md (about)

     1  ---
     2  sidebarTitle: "功能: Script 脚本"
     3  sidebarOrder: 5
     4  ---
     5  
     6  # Script 脚本
     7  
     8  Clash Premium 实现了基于 Python3 的脚本功能, 使用户能够以动态灵活的方式为数据包选择策略.
     9  
    10  您可以使用单个 Python 脚本控制整个规则匹配引擎, 也可以定义一些快捷方式, 并与常规规则一起使用. 本页介绍了第一种功能, 有关后者, 请参见[Script Shortcuts 脚本捷径](./script-shortcuts.md).
    11  
    12  ## 控制整个规则匹配引擎
    13  
    14  ```yaml
    15  mode: Script
    16  
    17  # https://lancellc.gitbook.io/clash/clash-config-file/script
    18  script:
    19    code: |
    20      def main(ctx, metadata):
    21        ip = metadata["dst_ip"] = ctx.resolve_ip(metadata["host"])
    22        if ip == "":
    23          return "DIRECT"
    24  
    25        code = ctx.geoip(ip)
    26        if code == "LAN" or code == "CN":
    27          return "DIRECT"
    28  
    29        return "Proxy" # default policy for requests which are not matched by any other script
    30  ```
    31  
    32  如果您想使用 IP 规则 (即: IP-CIDR、GEOIP 等) , 您首先需要手动解析 IP 地址并将其分配给 metadata:
    33  
    34  ```python
    35  def main(ctx, metadata):
    36      # ctx.rule_providers["geoip"].match(metadata) return false
    37  
    38      ip = ctx.resolve_ip(metadata["host"])
    39      if ip == "":
    40          return "DIRECT"
    41      metadata["dst_ip"] = ip
    42  
    43      # ctx.rule_providers["iprule"].match(metadata) return true
    44  
    45      return "Proxy"
    46  ```
    47  
    48  Metadata 和 Context 的接口定义:
    49  
    50  ```ts
    51  interface Metadata {
    52    type: string // socks5、http
    53    network: string // tcp
    54    host: string
    55    src_ip: string
    56    src_port: string
    57    dst_ip: string
    58    dst_port: string
    59    inbound_port: number
    60  }
    61  
    62  interface Context {
    63    resolve_ip: (host: string) => string // ip string
    64    resolve_process_name: (metadata: Metadata) => string
    65    resolve_process_path: (metadata: Metadata) => string
    66    geoip: (ip: string) => string // country code
    67    log: (log: string) => void
    68    proxy_providers: Record<string, Array<{ name: string, alive: boolean, delay: number }>>
    69    rule_providers: Record<string, { match: (metadata: Metadata) => boolean }>
    70  }
    71  ```