我有一个 namecheap 付费 vpn 服务,其中有数百个配置文件(ovpn conf 文件),每个配置文件都允许我拥有来自不同国家的 IP 地址。
我希望每小时在这些配置文件之间切换一次,选择一个新的 IP 并切换resolv.conf
为使用 VPN DNS 而不是我的(以避免 DNS 泄漏)。
另外,我只对美国 IP 地址感兴趣,因此过滤器会很好。
最后,我不想要后台服务;openvpn 客户端应该留在前台,在屏幕上打印所有信息消息,并且ctrl + c
应该终止它。
答案1
VPN网关-oneshot.sh
#!/bin/bash
# ------------------------------------------------------------------------------
# Each time this script is executed a random vpn config file is selected
# Better used with cron.hourly to switch IPs every hour
# Since i only use the vpn for netflix, there is a US filename filter
#
# A cada execucao deste script uma nova configuracao de vpn e escolhida
# Bom para ser usado em cron.hourly para trocar a cada hora
# Como meu uso de vpn e para netflix, estou filtrando para usar somente EUA
# ------------------------------------------------------------------------------
exec 2>&1
[ $UID -eq 0 ] || { echo "Not root. Exiting script." ; exit 1 ; }
SCRIPTPATH=$(readlink -f $0)
SCRIPTDIR=$(dirname $SCRIPTPATH)
SCRIPTNAME=$(basename $SCRIPTPATH .sh)
PIDFILE=/var/run/$SCRIPTNAME.pid
PWDFILE=$SCRIPTDIR/namecheap.login
openvpn=$(which openvpn) || apt install -y openvpn
rename=$(which rename) || apt install -y rename
cd $SCRIPTDIR
$rename -f -v 'y/ /-/' $SCRIPTDIR/tcp/*
POOL="$SCRIPTDIR/tcp/*-US-*.ovpn"
RNDMCFG=$(shuf -e ${POOL[@]} -n1)
echo "New random VPN conf selected: $RNDMCFG"
nmcli connection delete tun0
$openvpn --config $RNDMCFG --auth-user-pass $PWDFILE --writepid $PIDFILE --script-security 2 --up update-resolv-conf.sh --down update-resolv-conf.sh
更新解析配置文件
#!/bin/bash
# ------------------------------------------------------------------------------
# EN: Update resolv.conf to use the DNS defined by the VPN
# PT: Atualiza os DNS do resolv.conf para usar os definidos pela VPN
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# Get DNS defined by the VPN service
# Exit with error if the DNS array is empty
# ------------------------------------------------------------------------------
function getVpnDns() {
for frgn_optn in ${!foreign_option_*} ; do
for fo in "${!frgn_optn}" ; do
DNSARRAY+=( $(echo $fo | awk '/dhcp-option DNS/{print $3}') )
done
done
[ -z "$DNSARRAY" ] && exit 1
}
# ------------------------------------------------------------------------------
# Write DNS to resolv.conf
# ------------------------------------------------------------------------------
function writeResolvConf() {
getVpnDns
for DNS in ${DNSARRAY[@]} ; do
echo "nameserver $DNS"
done | tee /etc/resolv.conf
}
# ------------------------------------------------------------------------------
# Switch between resolv.conf configs on 'up' and 'down' events
# ------------------------------------------------------------------------------
case "$script_type" in
up)
mv -v /etc/resolv.conf /etc/resolv.conf.rag && writeResolvConf
;;
down)
mv -fv /etc/resolv.conf.rag /etc/resolv.conf
;;
esac