dotfiles/home/bin/executable_wgvpn

89 lines
2.1 KiB
Plaintext
Raw Normal View History

2023-05-07 02:19:41 +00:00
#!/bin/bash
# 檢查是否為 root user如果不是則使用 sudo 切換
if [[ $EUID -ne 0 ]]; then
exec sudo "$0" "$@"
exit
fi
# WireGuard 設定檔案資料夾
wg_conf_folder="/etc/wireguard/"
# 列出所有可使用的設定檔案
function list_conf_files() {
echo "可用的 WireGuard 設定檔案:"
ls -1 $wg_conf_folder | grep ".conf$"
}
# 連線到指定的 VPN
function connect() {
local intf=$1
# 切斷其他已連線的 VPN
if [[ $1 == "--disconnect-others" ]] || [[ $1 == "-d" ]] ; then
wg-quick down "$(wg show | grep "interface:" | awk '{print $2}')"
intf=$2
fi
# 確認設定檔案是否存在
if [[ ! -f "$wg_conf_folder/$intf.conf" ]]; then
echo "找不到 $wg_conf_folder/$intf.conf"
exit
fi
# 連線 VPN
wg-quick up "$wg_conf_folder/$intf.conf"
echo "已連線到 $intf"
}
# 斷開指定的 VPN若未指定則斷開所有 VPN
function disconnect() {
if [[ -n "$1" ]]; then
wg-quick down "$1"
echo "已斷開 $1"
else
wg-quick down "$(wg show | grep "interface:" | awk '{print $2}')"
echo "已斷開所有 VPN"
fi
}
# 列出已連線的 VPN
function list_connections() {
echo "已連線的 VPN"
wg show | grep "interface:" | awk '{print $2}'
}
# 判斷參數是否為空
if [[ -z $1 ]]; then
echo "使用方式:"
echo " $0 list - 列出所有可使用的設定檔案"
echo " $0 connect <config> [-d|--disconnect-others] - 連線到指定的 VPN"
echo " $0 disconnect [interface] - 斷開指定的 VPN若未指定則斷開所有 VPN"
echo " $0 list-connections - 列出已連線的 VPN"
exit
fi
case "$1" in
list)
list_conf_files
;;
connect)
if [[ -n $2 ]]; then
connect "$2" "$3"
else
echo "請輸入要連線的 VPN 設定檔案名稱"
fi
;;
disconnect)
disconnect "$2"
;;
list-connections)
list_connections
;;
*)
echo "無效的參數:$1"
exit
;;
esac
# vim: set ft=sh :