Search code examples
bashproxysquid

linux bash - dynamically update config file for squid service


I have created a bash script that checks some proxy servers i want to use in squid as forwarding proxies:

#!/bin/sh

PROXY_LIST="1.1.1.1:3128 1.2.2.2:3128"
CHECK_URL="https://google.com"
SQUID_CFG="/etc/squid/squid.conf"

for proxy in $PROXY_LIST; do
curl -s -k -x http://$proxy -I $CHECK_URL > /dev/null

if [ $? == 0 ]; then
  echo "Proxy $proxy is working!"
  echo $proxy > proxy-good.txt
else
  echo "Proxy $proxy is bad!"
  echo $proxy > proxy-bad.txt
fi
done

#update config
#service squid reload

The static config in squid looks like this:

cache_peer 1.1.1.1 parent 3128 0 no-query default
cache_peer 1.2.2.2 parent 3128 0 no-query default

What is the best way to update the config file from my bash script when ever a proxy is bad or good and how can I do that in bash or other programming language?


Solution

  • #!/bin/sh
    
    PROXY_LIST="1.1.1.1:3128 1.2.2.2:3128"
    CHECK_URL="https://google.com"
    SQUID_CFG="/etc/squid/squid.conf"
    
    for proxy in $PROXY_LIST; do
    curl -s -k -x http://$proxy -I $CHECK_URL > /dev/null
    
    if [ $? == 0 ]; then
      echo "Proxy $proxy is working!"
      echo $proxy > proxy-good.txt
      echo "cache_peer ${proxy%%:*} parent ${proxy##*:} 0 no-query default" >> "$SQUID_CONFIG"
      # ${proxy%%:*} - represents the IP address
      # ${proxy##*:} - represents the port
      # Add the cache peer line to the end of the squid config file
    else
      echo "Proxy $proxy is bad!"
      echo $proxy > proxy-bad.txt
      sed -i "/^cache_peer ${proxy%%:*} parent ${proxy##*:} 0 no-query default/d" "$SQUID_CONFIG"
      # Use the port and IP with sed to search for the cache peer line and then delete.
    fi
    done