Jayden

Jayden

PAC (Proxy Auto-Config)

I have been troubled by one thing for a long time:

  • I am a heavy macOS user and it is easy for me to solve almost all network problems on macOS, thanks to excellent software like Surge for Mac.

  • However, things are more complicated on Windows and Linux, but using Windows or Linux is still necessary.

  • I don't want to deploy software and write configuration files for each system.

Therefore, the best practice is to use Surge for Mac as a proxy server to take over the network for other devices.

I am in a large intranet at school and cannot set the IP of my Mac to static, so I need to constantly update the IP address of my Mac to maintain this solution.

With the help of ChatGPT, I wrote a script that automatically obtains the IP address of my Mac and generates a PAC (Proxy Auto-Config) configuration file, which is uploaded to my cloud storage. Other devices only need to fill in the address of the configuration file.


  1. Save the following code as generate_pac.sh. This script will generate a proxy.pac file in the same directory and upload it to the cloud storage using the webdav feature of alist.

    #!/bin/zsh
    
    cd /Users/jayden/proxy_pac
    # Ensure consistent environment variables to successfully obtain the IP address.
    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.log
    
  2. Set up a scheduled task:

    crontab -e
    

    Then add this line to the end (run every half hour, you can adjust it according to your needs):

    30 * * * * /Users/jayden/proxy_pac/generate_pac.sh
    

This article is synchronized and updated to xLog by Mix Space.
The original link is https://xxu.do/posts/geek/PAC


Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.