Clash Premium 實作了基於 Python3 的指令碼功能,使使用者能夠以動態靈活的方式為資料包選擇策略。
您可以使用單一 Python 指令碼控制整個規則比對引擎,也可以定義捷徑並搭配一般規則使用。本頁介紹前者;如需瞭解後者,請參閱Script Shortcuts 指令碼捷徑。
控制整個規則匹配引擎
yaml
mode: Script
# https://lancellc.gitbook.io/clash/clash-config-file/script
script:
code: |
def main(ctx, metadata):
ip = metadata["dst_ip"] = ctx.resolve_ip(metadata["host"])
if ip == "":
return "DIRECT"
code = ctx.geoip(ip)
if code == "LAN" or code == "CN":
return "DIRECT"
return "Proxy" # default policy for requests which are not matched by any other script如果您想使用 IP 規則(即:IP-CIDR、GEOIP 等),您首先需要手動解析 IP 位址並將其分配給 metadata:
python
def main(ctx, metadata):
# ctx.rule_providers["geoip"].match(metadata) return false
ip = ctx.resolve_ip(metadata["host"])
if ip == "":
return "DIRECT"
metadata["dst_ip"] = ip
# ctx.rule_providers["iprule"].match(metadata) return true
return "Proxy"Metadata 和 Context 的介面定義:
ts
interface Metadata {
type: string // socks5、http
network: string // tcp
host: string
src_ip: string
src_port: string
dst_ip: string
dst_port: string
inbound_port: number
}
interface Context {
resolve_ip: (host: string) => string // ip string
resolve_process_name: (metadata: Metadata) => string
resolve_process_path: (metadata: Metadata) => string
geoip: (ip: string) => string // country code
log: (log: string) => void
proxy_providers: Record<string, Array<{ name: string, alive: boolean, delay: number }>>
rule_providers: Record<string, { match: (metadata: Metadata) => boolean }>
}