Something has been bothering me for a long time:
- I'm a heavy macOS user. Thanks to excellent macOS software like Surge for Mac, I can solve almost any network problem with ease.
But on Windows and Linux, things get considerably more complicated—and using Windows or Linux is still necessary.
I don't want to install a separate piece of software on every system and write a config file for each one.
Therefore, the best approach is to use Surge for Mac as a proxy server to take over networking for other devices.
I'm on a large campus intranet and can't assign a static IP to my Mac, so I have to keep updating the Mac's IP address to keep this setup working.
With ChatGPT's help, I wrote a script that automatically fetches the Mac's IP address, generates a PAC (Proxy Auto-Config) configuration file, and uploads it to my cloud drive. Other devices just need to enter the URL of the configuration file.
Save the following code as
generate_pac.sh. The script generates aproxy.pacfile in the same directory and uploads it to the cloud drive using Alist's WebDAV feature.Shell#!/bin/zsh cd /Users/jayden/proxy_pac # 保证环境变量的一致以成功获取到 ip 地址。 PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin rm -f proxy.pac # Get the local IP address from interface en0 (commonly used for Wi-Fi) LOCAL_IP=$(ipconfig getifaddr en0) # Proxy ports HTTP_PROXY_PORT=6152 SOCKS_PROXY_PORT=6153 # PAC file path PAC_FILE="proxy.pac" # Generate the PAC file cat <<EOL > $PAC_FILE function FindProxyForURL(url, host) { var http_proxy = "PROXY $LOCAL_IP:$HTTP_PROXY_PORT"; var socks_proxy = "SOCKS5 $LOCAL_IP:$SOCKS_PROXY_PORT"; // Add your proxy rules here if (shExpMatch(host, "*.example.com")) { return "DIRECT"; // Direct connection } // Default to using HTTP proxy return http_proxy + "; " + socks_proxy; } EOL echo "PAC file generated at $PAC_FILE" >> proxy_pac.log # Upload the PAC file to Alist via WebDAV curl -X DELETE https://pan.xxu.do/dav/path/to/proxy.pac -u username:password curl -T $PAC_FILE https://pan.xxu.do/dav/path/to/proxy.pac -u username:password echo "PAC file generated and uploaded to Alist" >> proxy_pac.log date >> proxy_pac.logSet up a scheduled task:
Shellcrontab -eThen add this line to the end (it runs every hour at the half-hour mark; feel free to adjust it to your needs):
CRON30 * * * * /Users/jayden/proxy_pac/generate_pac.sh