github.com/igoogolx/clash@v1.19.8/docs/premium/script.md (about) 1 --- 2 sidebarTitle: "Feature: Script" 3 sidebarOrder: 5 4 --- 5 6 # Script 7 8 Clash Premium implements the Scripting feature powered by Python3, enableing users to programmatically select policies for the packets with dynamic flexibility. 9 10 You can either control the entire rule-matching engine with a single Python script, or define a number of shortcuts and use them in companion with the regular rules. This page refers to the first feature, for the latter, see [Script Shortcuts](./script-shortcuts.md). 11 12 ## Scripting the entire rule-matching engine 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 = ctx.resolve_ip(metadata["host"]) 22 if ip == "": 23 return "DIRECT" 24 metadata["dst_ip"] = ip 25 26 code = ctx.geoip(ip) 27 if code == "LAN" or code == "CN": 28 return "DIRECT" 29 30 return "Proxy" # default policy for requests which are not matched by any other script 31 ``` 32 33 If you want to use ip rules (i.e.: IP-CIDR, GEOIP, etc), you will first need to manually resolve IP addresses and assign them to metadata: 34 35 ```python 36 def main(ctx, metadata): 37 # ctx.rule_providers["geoip"].match(metadata) return false 38 39 ip = ctx.resolve_ip(metadata["host"]) 40 if ip == "": 41 return "DIRECT" 42 metadata["dst_ip"] = ip 43 44 # ctx.rule_providers["iprule"].match(metadata) return true 45 46 return "Proxy" 47 ``` 48 49 Interface definition for Metadata and Context: 50 51 ```ts 52 interface Metadata { 53 type: string // socks5、http 54 network: string // tcp 55 host: string 56 src_ip: string 57 src_port: string 58 dst_ip: string 59 dst_port: string 60 inbound_port: number 61 } 62 63 interface Context { 64 resolve_ip: (host: string) => string // ip string 65 resolve_process_name: (metadata: Metadata) => string 66 resolve_process_path: (metadata: Metadata) => string 67 geoip: (ip: string) => string // country code 68 log: (log: string) => void 69 proxy_providers: Record<string, Array<{ name: string, alive: boolean, delay: number }>> 70 rule_providers: Record<string, { match: (metadata: Metadata) => boolean }> 71 } 72 ```