一、环境说明

本文整理了 Debian / Ubuntu 下 OCServ 的依赖安装命令,以及客户端服务器列表的配置示例。

附录提供 OCServ 1.4.1 管理脚本,脚本标记版本为 1.4.1-2fa。

二、安装依赖

以下命令需要以具有软件安装权限的账号执行。

1. 基础编译工具

apt-get install -y build-essential pkg-config

2. 必需依赖

apt-get install -y libgnutls28-dev libev-dev

3. 可选功能与测试依赖

以下软件包用于扩展功能或测试,可根据实际需要安装。

apt-get install -y \
    libpam0g-dev \
    liblz4-dev \
    libseccomp-dev \
    libreadline-dev \
    libnl-route-3-dev \
    libkrb5-dev \
    libradcli-dev \
    libcurl4-gnutls-dev \
    libcjose-dev \
    libjansson-dev \
    liboath-dev \
    libprotobuf-c-dev \
    libtalloc-dev \
    libllhttp-dev \
    protobuf-c-compiler \
    gperf \
    iperf3 \
    lcov \
    libuid-wrapper \
    libpam-wrapper \
    libnss-wrapper \
    libsocket-wrapper \
    gss-ntlmssp \
    haproxy \
    iputils-ping \
    freeradius \
    gawk \
    gnutls-bin \
    iproute2 \
    yajl-tools \
    tcpdump

附录脚本的依赖说明

附录脚本使用 --with-liboath 编译参数,并调用 certtool 和 Python 辅助程序。因此,使用该脚本时,不能将 liboath-dev、gnutls-bin 和 python3 一概视为可省略项。

4. 手册生成工具

需要生成 man 手册时,安装:

apt-get install -y ronn

三、客户端服务器列表配置

1. 编辑配置文件

使用以下命令打开配置文件:

vi /var/lib/ocserv/profile.xml

2. 修改服务器列表

在现有 XML 配置中找到 ServerList 节点,按需修改服务器名称和地址。

以下内容为服务器列表片段,不是完整的客户端配置文件:

<ServerList>
    <HostEntry>
        <HostName>服务器描述1</HostName>
        <HostAddress>server1_ipaddress:port</HostAddress>
    </HostEntry>

    <HostEntry>
        <HostName>服务器描述2</HostName>
        <HostAddress>server2_ipaddress:port</HostAddress>
    </HostEntry>
</ServerList>

3. 字段说明

  • ServerList:服务器列表。
  • HostEntry:一个服务器条目;多个服务器分别使用独立条目。
  • HostName:客户端中显示的服务器名称。
  • HostAddress:原文示例中的服务器地址与端口占位内容,使用前请替换。
服务器列表能否下发给客户端,还需要结合 OCServ 的配置和客户端支持情况确认。本文仅整理所提供的 XML 片段。

4. 保存并退出

在 vi 中按下 Esc,输入以下命令并回车:

:wq

四、附录:OCServ 管理脚本

脚本说明

脚本包含以下功能入口:

  • OCServ 的编译安装与卸载。
  • 服务启动、停止与重启。
  • 用户账号的添加、删除、启用与禁用。
  • 配置文件编辑及日志查看。
  • Google Authenticator 绑定功能入口。

辅助文件说明

双重认证功能依赖同目录下的 ocserv-2fa-user.py。本文未包含该辅助程序,仅凭下方 Bash 脚本无法完成该功能。

以下为公开整理版:已移除个人署名、取消固定默认用户名和密码,并将密码输入改为隐藏输入及二次确认。其余脚本逻辑保留,未执行安装验证。

完整脚本

#!/usr/bin/env bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

#=================================================
#    System Required: Debian/Ubuntu
#    Description: ocserv AnyConnect
#    Version: 1.4.1
#=================================================
sh_ver="1.4.1-2fa"
file="/usr/local/sbin/ocserv"
conf_file="/etc/ocserv"
conf="/etc/ocserv/ocserv.conf"
passwd_file="/etc/ocserv/ocpasswd"
log_file="/tmp/ocserv.log"
ocserv_ver="1.4.1"
PID_FILE="/var/run/ocserv.pid"

Green_font_prefix="\033[32m" && Red_font_prefix="\033[31m" && Green_background_prefix="\033[42;37m" && Red_background_prefix="\033[41;37m" && Font_color_suffix="\033[0m"
Info="${Green_font_prefix}[信息]${Font_color_suffix}"
Error="${Red_font_prefix}[错误]${Font_color_suffix}"
Tip="${Green_font_prefix}[注意]${Font_color_suffix}"

check_root(){
    [[ $EUID != 0 ]] && echo -e "${Error} 当前非ROOT账号(或没有ROOT权限),无法继续操作,请更换ROOT账号或使用 ${Green_background_prefix}sudo su${Font_color_suffix} 命令获取临时ROOT权限(执行后可能会提示输入当前账号的密码)。" && exit 1
}
#检查系统
check_sys(){
    if [[ -f /etc/redhat-release ]]; then
        release="centos"
    elif cat /etc/issue | grep -q -E -i "debian"; then
        release="debian"
    elif cat /etc/issue | grep -q -E -i "ubuntu"; then
        release="ubuntu"
    elif cat /etc/issue | grep -q -E -i "centos|red hat|redhat"; then
        release="centos"
    elif cat /proc/version | grep -q -E -i "debian"; then
        release="debian"
    elif cat /proc/version | grep -q -E -i "ubuntu"; then
        release="ubuntu"
    elif cat /proc/version | grep -q -E -i "centos|red hat|redhat"; then
        release="centos"
    fi
    #bit=`uname -m`
}
check_installed_status(){
    [[ ! -e ${file} ]] && echo -e "${Error} ocserv 没有安装,请检查 !" && exit 1
    [[ ! -e ${conf} ]] && echo -e "${Error} ocserv 配置文件不存在,请检查 !" && [[ $1 != "un" ]] && exit 1
}
check_pid(){
    if [[ ! -e ${PID_FILE} ]]; then
        PID=""
    else
        PID=$(cat ${PID_FILE})
    fi
}
Get_ip(){
    ip=$(wget -qO- -t1 -T2 ipinfo.io/ip)
    if [[ -z "${ip}" ]]; then
        ip=$(wget -qO- -t1 -T2 api.ip.sb/ip)
        if [[ -z "${ip}" ]]; then
            ip=$(wget -qO- -t1 -T2 members.3322.org/dyndns/getip)
            if [[ -z "${ip}" ]]; then
                ip="VPS_IP"
            fi
        fi
    fi
}
Download_ocserv(){
    mkdir "ocserv" && cd "ocserv"
    wget --no-check-certificate "https://www.infradead.org/ocserv/download/ocserv-1.4.1.tar.xz"
    [[ ! -s "ocserv-1.4.1.tar.xz" ]] && echo -e "${Error} ocserv 源码文件下载失败 !" && rm -rf "ocserv/" && rm -rf "ocserv-1.4.1.tar.xz" && exit 1
    tar -xJf ocserv-1.4.1.tar.xz && cd ocserv-1.4.1
    ./configure --with-liboath || exit 1
    make
    make install
    cd .. && cd ..
    rm -rf ocserv/
    
    if [[ -e ${file} ]]; then
        mkdir "${conf_file}"
        wget --no-check-certificate -N -P "${conf_file}" "https://raw.githubusercontent.com/ToyoDAdoubiBackup/doubi/master/other/ocserv.conf"
        [[ ! -s "${conf}" ]] && echo -e "${Error} ocserv 配置文件下载失败 !" && rm -rf "${conf_file}" && exit 1
    else
        echo -e "${Error} ocserv 编译安装失败,请检查!" && exit 1
    fi
}
Service_ocserv(){
    if ! wget --no-check-certificate https://raw.githubusercontent.com/ToyoDAdoubiBackup/doubi/master/service/ocserv_debian -O /etc/init.d/ocserv; then
        echo -e "${Error} ocserv 服务 管理脚本下载失败 !" && over
    fi
    chmod +x /etc/init.d/ocserv
    update-rc.d -f ocserv defaults
    echo -e "${Info} ocserv 服务 管理脚本下载完成 !"
}
rand(){
    min=10000
    max=$((60000-$min+1))
    num=$(date +%s%N)
    echo $(($num%$max+$min))
}
Generate_SSL(){
    lalala=$(rand)
    mkdir /tmp/ssl && cd /tmp/ssl
    echo -e 'cn = "'${lalala}'"
organization = "'${lalala}'"
serial = 1
expiration_days = 365
ca
signing_key
cert_signing_key
crl_signing_key' > ca.tmpl
    [[ $? != 0 ]] && echo -e "${Error} 写入SSL证书签名模板失败(ca.tmpl) !" && over
    certtool --generate-privkey --outfile ca-key.pem
    [[ $? != 0 ]] && echo -e "${Error} 生成SSL证书密匙文件失败(ca-key.pem) !" && over
    certtool --generate-self-signed --load-privkey ca-key.pem --template ca.tmpl --outfile ca-cert.pem
    [[ $? != 0 ]] && echo -e "${Error} 生成SSL证书文件失败(ca-cert.pem) !" && over
    
    Get_ip
    if [[ -z "$ip" ]]; then
        echo -e "${Error} 检测外网IP失败 !"
        read -e -p "请手动输入你的服务器外网IP:" ip
        [[ -z "${ip}" ]] && echo "取消..." && over
    fi
    echo -e 'cn = "'${ip}'"
organization = "'${lalala}'"
expiration_days = 365
signing_key
encryption_key
tls_www_server' > server.tmpl
    [[ $? != 0 ]] && echo -e "${Error} 写入SSL证书签名模板失败(server.tmpl) !" && over
    certtool --generate-privkey --outfile server-key.pem
    [[ $? != 0 ]] && echo -e "${Error} 生成SSL证书密匙文件失败(server-key.pem) !" && over
    certtool --generate-certificate --load-privkey server-key.pem --load-ca-certificate ca-cert.pem --load-ca-privkey ca-key.pem --template server.tmpl --outfile server-cert.pem
    [[ $? != 0 ]] && echo -e "${Error} 生成SSL证书文件失败(server-cert.pem) !" && over
    
    mkdir /etc/ocserv/ssl
    mv ca-cert.pem /etc/ocserv/ssl/ca-cert.pem
    mv ca-key.pem /etc/ocserv/ssl/ca-key.pem
    mv server-cert.pem /etc/ocserv/ssl/server-cert.pem
    mv server-key.pem /etc/ocserv/ssl/server-key.pem
    cd .. && rm -rf /tmp/ssl/
}
Installation_dependency(){
    [[ ! -e "/dev/net/tun" ]] && echo -e "${Error} 你的VPS没有开启TUN,请联系IDC或通过VPS控制面板打开TUN/TAP开关 !" && exit 1
    if [[ ${release} = "centos" ]]; then
        echo -e "${Error} 本脚本不支持 CentOS 系统 !" && exit 1
    elif [[ ${release} = "debian" ]]; then
        cat /etc/issue |grep 9\..*>/dev/null
        if [[ $? = 0 ]]; then
            apt-get update
            apt-get install vim net-tools pkg-config build-essential libgnutls28-dev libwrap0-dev liblz4-dev libseccomp-dev libreadline-dev libnl-nf-3-dev libev-dev gnutls-bin liboath-dev python3 -y
        else
            mv /etc/apt/sources.list /etc/apt/sources.list.bak
            wget --no-check-certificate -O "/etc/apt/sources.list" "https://raw.githubusercontent.com/ToyoDAdoubiBackup/doubi/master/sources/us.sources.list"
            apt-get update
            apt-get install vim net-tools pkg-config build-essential libgnutls28-dev libwrap0-dev liblz4-dev libseccomp-dev libreadline-dev libnl-nf-3-dev libev-dev gnutls-bin liboath-dev python3 -y
            rm -rf /etc/apt/sources.list
            mv /etc/apt/sources.list.bak /etc/apt/sources.list
            apt-get update
        fi
    else
        apt-get update
        apt-get install vim net-tools pkg-config build-essential libgnutls28-dev libwrap0-dev liblz4-dev libseccomp-dev libreadline-dev libnl-nf-3-dev libev-dev gnutls-bin liboath-dev python3 -y
    fi
}
Install_ocserv(){
    check_root
    [[ -e ${file} ]] && echo -e "${Error} ocserv 已安装,请检查 !" && exit 1
    echo -e "${Info} 开始安装/配置 依赖..."
    Installation_dependency
    echo -e "${Info} 开始下载/安装 配置文件..."
    Download_ocserv
    echo -e "${Info} 开始下载/安装 服务脚本(init)..."
    Service_ocserv
    echo -e "${Info} 开始自签SSL证书..."
    Generate_SSL
    echo -e "${Info} 开始设置账号配置..."
    Read_config
    Set_Config
    echo -e "${Info} 开始设置 iptables防火墙..."
    Set_iptables
    echo -e "${Info} 开始添加 iptables防火墙规则..."
    Add_iptables
    echo -e "${Info} 开始保存 iptables防火墙规则..."
    Save_iptables
    echo -e "${Info} 所有步骤 安装完毕,开始启动..."
    Start_ocserv
}
Start_ocserv(){
    check_installed_status
    check_pid
    [[ ! -z ${PID} ]] && echo -e "${Error} ocserv 正在运行,请检查 !" && exit 1
    /etc/init.d/ocserv start
    sleep 2s
    check_pid
    [[ ! -z ${PID} ]] && View_Config
}
Stop_ocserv(){
    check_installed_status
    check_pid
    [[ -z ${PID} ]] && echo -e "${Error} ocserv 没有运行,请检查 !" && exit 1
    /etc/init.d/ocserv stop
}
Restart_ocserv(){
    check_installed_status
    check_pid
    [[ ! -z ${PID} ]] && /etc/init.d/ocserv stop
    /etc/init.d/ocserv start
    sleep 2s
    check_pid
    [[ ! -z ${PID} ]] && View_Config
}
Set_ocserv(){
    [[ ! -e ${conf} ]] && echo -e "${Error} ocserv 配置文件不存在 !" && exit 1
    tcp_port=$(cat ${conf}|grep "tcp-port ="|awk -F ' = ' '{print $NF}')
    udp_port=$(cat ${conf}|grep "udp-port ="|awk -F ' = ' '{print $NF}')
    vim ${conf}
    set_tcp_port=$(cat ${conf}|grep "tcp-port ="|awk -F ' = ' '{print $NF}')
    set_udp_port=$(cat ${conf}|grep "udp-port ="|awk -F ' = ' '{print $NF}')
    Del_iptables
    Add_iptables
    Save_iptables
    echo "是否重启 ocserv ? (Y/n)"
    read -e -p "(默认: Y):" yn
    [[ -z ${yn} ]] && yn="y"
    if [[ ${yn} == [Yy] ]]; then
        Restart_ocserv
    fi
}
Set_username(){
    while true; do
        read -r -p "请输入 VPN 用户名(必填): " username
        if [[ -n "$username" ]]; then
            break
        fi
        echo "用户名不能为空。"
    done
}
Set_passwd(){
    local userpass_confirm
    while true; do
        read -r -s -p "请输入 VPN 密码(必填,输入不显示): " userpass
        printf '\n'
        if [[ -z "$userpass" ]]; then
            echo "密码不能为空。"
            continue
        fi
        read -r -s -p "请再次输入 VPN 密码: " userpass_confirm
        printf '\n'
        if [[ "$userpass" == "$userpass_confirm" ]]; then
            unset userpass_confirm
            break
        fi
        echo "两次密码不一致,请重新输入。"
    done
}
Set_tcp_port(){
    while true
    do
    echo -e "请输入VPN服务端的TCP端口"
    read -e -p "(默认: 443):" set_tcp_port
    [[ -z "$set_tcp_port" ]] && set_tcp_port="443"
    echo $((${set_tcp_port}+0)) &>/dev/null
    if [[ $? -eq 0 ]]; then
        if [[ ${set_tcp_port} -ge 1 ]] && [[ ${set_tcp_port} -le 65535 ]]; then
            echo && echo -e "    TCP端口 : ${Red_font_prefix}${set_tcp_port}${Font_color_suffix}" && echo
            break
        else
            echo -e "${Error} 请输入正确的数字!"
        fi
    else
        echo -e "${Error} 请输入正确的数字!"
    fi
    done
}
Set_udp_port(){
    while true
    do
    echo -e "请输入VPN服务端的UDP端口"
    read -e -p "(默认: ${set_tcp_port}):" set_udp_port
    [[ -z "$set_udp_port" ]] && set_udp_port="${set_tcp_port}"
    echo $((${set_udp_port}+0)) &>/dev/null
    if [[ $? -eq 0 ]]; then
        if [[ ${set_udp_port} -ge 1 ]] && [[ ${set_udp_port} -le 65535 ]]; then
            echo && echo -e "    TCP端口 : ${Red_font_prefix}${set_udp_port}${Font_color_suffix}" && echo
            break
        else
            echo -e "${Error} 请输入正确的数字!"
        fi
    else
        echo -e "${Error} 请输入正确的数字!"
    fi
    done
}
Set_Config(){
    Set_username
    Set_passwd
    echo -e "${userpass}\n${userpass}"|ocpasswd -c ${passwd_file} ${username}
    Set_tcp_port
    Set_udp_port
    sed -i 's/tcp-port = '"$(echo ${tcp_port})"'/tcp-port = '"$(echo ${set_tcp_port})"'/g' ${conf}
    sed -i 's/udp-port = '"$(echo ${udp_port})"'/udp-port = '"$(echo ${set_udp_port})"'/g' ${conf}
}
Read_config(){
    [[ ! -e ${conf} ]] && echo -e "${Error} ocserv 配置文件不存在 !" && exit 1
    conf_text=$(cat ${conf}|grep -v '#')
    tcp_port=$(echo -e "${conf_text}"|grep "tcp-port ="|awk -F ' = ' '{print $NF}')
    udp_port=$(echo -e "${conf_text}"|grep "udp-port ="|awk -F ' = ' '{print $NF}')
    max_same_clients=$(echo -e "${conf_text}"|grep "max-same-clients ="|awk -F ' = ' '{print $NF}')
    max_clients=$(echo -e "${conf_text}"|grep "max-clients ="|awk -F ' = ' '{print $NF}')
}
List_User(){
    [[ ! -e ${passwd_file} ]] && echo -e "${Error} ocserv 账号配置文件不存在 !" && exit 1
    User_text=$(cat ${passwd_file})
    if [[ ! -z ${User_text} ]]; then
        User_num=$(echo -e "${User_text}"|wc -l)
        user_list_all=""
        for((integer = 1; integer <= ${User_num}; integer++))
        do
            user_name=$(echo -e "${User_text}" | awk -F ':*:' '{print $1}' | sed -n "${integer}p")
            user_status=$(echo -e "${User_text}" | awk -F ':*:' '{print $NF}' | sed -n "${integer}p"|cut -c 1)
            if [[ ${user_status} == '!' ]]; then
                user_status="禁用"
            else
                user_status="启用"
            fi
            user_list_all=${user_list_all}"用户名: "${user_name}" 账号状态: "${user_status}"\n"
        done
        echo && echo -e "用户总数 ${Green_font_prefix}"${User_num}"${Font_color_suffix}"
        echo -e ${user_list_all}
    fi
}
Add_User(){
    Set_username
    Set_passwd
    user_status=$(cat "${passwd_file}"|grep "${username}"':*:')
    [[ ! -z ${user_status} ]] && echo -e "${Error} 用户名已存在 ![ ${username} ]" && exit 1
    echo -e "${userpass}\n${userpass}"|ocpasswd -c ${passwd_file} ${username}
    user_status=$(cat "${passwd_file}"|grep "${username}"':*:')
    if [[ ! -z ${user_status} ]]; then
        echo -e "${Info} 账号添加成功 ![ ${username} ]"
        if grep -q '^[[:space:]]*auth.*otp=/etc/ocserv/users.oath' "$conf"; then
            local helper="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/ocserv-2fa-user.py"
            if ! python3 "$helper" "$username"; then
                echo "动态码绑定失败;该 VPN 用户在完成绑定前无法登录。"
                return 1
            fi
        fi
    else
        echo -e "${Error} 账号添加失败 ![ ${username} ]" && exit 1
    fi
}
Del_User(){
    List_User
    [[ ${User_num} == 1 ]] && echo -e "${Error} 当前仅剩一个账号配置,无法删除 !" && exit 1
    echo -e "请输入要删除的VPN账号的用户名"
    read -e -p "(默认取消):" Del_username
    [[ -z "${Del_username}" ]] && echo "已取消..." && exit 1
    user_status=$(cat "${passwd_file}"|grep "${Del_username}"':*:')
    [[ -z ${user_status} ]] && echo -e "${Error} 用户名不存在 ! [${Del_username}]" && exit 1
    ocpasswd -c ${passwd_file} -d ${Del_username}
    user_status=$(cat "${passwd_file}"|grep "${Del_username}"':*:')
    if [[ -z ${user_status} ]]; then
        echo -e "${Info} 删除成功 ! [${Del_username}]"
    else
        echo -e "${Error} 删除失败 ! [${Del_username}]" && exit 1
    fi
}
Modify_User_disabled(){
    List_User
    echo -e "请输入要启用/禁用的VPN账号的用户名"
    read -e -p "(默认取消):" Modify_username
    [[ -z "${Modify_username}" ]] && echo "已取消..." && exit 1
    user_status=$(cat "${passwd_file}"|grep "${Modify_username}"':*:')
    [[ -z ${user_status} ]] && echo -e "${Error} 用户名不存在 ! [${Modify_username}]" && exit 1
    user_status=$(cat "${passwd_file}" | grep "${Modify_username}"':*:' | awk -F ':*:' '{print $NF}' |cut -c 1)
    if [[ ${user_status} == '!' ]]; then
            ocpasswd -c ${passwd_file} -u ${Modify_username}
            user_status=$(cat "${passwd_file}" | grep "${Modify_username}"':*:' | awk -F ':*:' '{print $NF}' |cut -c 1)
            if [[ ${user_status} != '!' ]]; then
                echo -e "${Info} 启用成功 ! [${Modify_username}]"
            else
                echo -e "${Error} 启用失败 ! [${Modify_username}]" && exit 1
            fi
        else
            ocpasswd -c ${passwd_file} -l ${Modify_username}
            user_status=$(cat "${passwd_file}" | grep "${Modify_username}"':*:' | awk -F ':*:' '{print $NF}' |cut -c 1)
            if [[ ${user_status} == '!' ]]; then
                echo -e "${Info} 禁用成功 ! [${Modify_username}]"
            else
                echo -e "${Error} 禁用失败 ! [${Modify_username}]" && exit 1
            fi
        fi
}
Set_Pass(){
    check_installed_status
    echo && echo -e " 你要做什么?
    
 ${Green_font_prefix} 0.${Font_color_suffix} 列出 账号配置
————————
 ${Green_font_prefix} 1.${Font_color_suffix} 添加 账号配置
 ${Green_font_prefix} 2.${Font_color_suffix} 删除 账号配置
————————
 ${Green_font_prefix} 3.${Font_color_suffix} 启用/禁用 账号配置
 
 注意:添加/修改/删除 账号配置后,VPN服务端会实时读取,无需重启服务端 !" && echo
    read -e -p "(默认: 取消):" set_num
    [[ -z "${set_num}" ]] && echo "已取消..." && exit 1
    if [[ ${set_num} == "0" ]]; then
        List_User
    elif [[ ${set_num} == "1" ]]; then
        Add_User
    elif [[ ${set_num} == "2" ]]; then
        Del_User
    elif [[ ${set_num} == "3" ]]; then
        Modify_User_disabled
    else
        echo -e "${Error} 请输入正确的数字[1-3]" && exit 1
    fi
}
View_Config(){
    Get_ip
    Read_config
    clear && echo "===================================================" && echo
    echo -e " AnyConnect 配置信息:" && echo
    echo -e " I  P\t\t  : ${Green_font_prefix}${ip}${Font_color_suffix}"
    echo -e " TCP端口\t  : ${Green_font_prefix}${tcp_port}${Font_color_suffix}"
    echo -e " UDP端口\t  : ${Green_font_prefix}${udp_port}${Font_color_suffix}"
    echo -e " 单用户设备数限制 : ${Green_font_prefix}${max_same_clients}${Font_color_suffix}"
    echo -e " 总用户设备数限制 : ${Green_font_prefix}${max_clients}${Font_color_suffix}"
    echo -e "\n 客户端链接请填写 : ${Green_font_prefix}${ip}:${tcp_port}${Font_color_suffix}"
    echo && echo "==================================================="
}
View_Log(){
    [[ ! -e ${log_file} ]] && echo -e "${Error} ocserv 日志文件不存在 !" && exit 1
    echo && echo -e "${Tip} 按 ${Red_font_prefix}Ctrl+C${Font_color_suffix} 终止查看日志" && echo -e "如果需要查看完整日志内容,请用 ${Red_font_prefix}cat ${log_file}${Font_color_suffix} 命令。" && echo
    tail -f ${log_file}
}
Uninstall_ocserv(){
    check_installed_status "un"
    echo "确定要卸载 ocserv ? (y/N)"
    echo
    read -e -p "(默认: n):" unyn
    [[ -z ${unyn} ]] && unyn="n"
    if [[ ${unyn} == [Yy] ]]; then
        check_pid
        [[ ! -z $PID ]] && kill -9 ${PID} && rm -f ${PID_FILE}
        Read_config
        Del_iptables
        Save_iptables
        update-rc.d -f ocserv remove
        rm -rf /etc/init.d/ocserv
        rm -rf "${conf_file}"
        rm -rf "${log_file}"
        cd '/usr/local/bin' && rm -f occtl
        rm -f ocpasswd
        cd '/usr/local/bin' && rm -f ocserv-fw
        cd '/usr/local/sbin' && rm -f ocserv
        cd '/usr/local/share/man/man8' && rm -f ocserv.8
        rm -f ocpasswd.8
        rm -f occtl.8
        echo && echo "ocserv 卸载完成 !" && echo
    else
        echo && echo "卸载已取消..." && echo
    fi
}
over(){
    update-rc.d -f ocserv remove
    rm -rf /etc/init.d/ocserv
    rm -rf "${conf_file}"
    rm -rf "${log_file}"
    cd '/usr/local/bin' && rm -f occtl
    rm -f ocpasswd
    cd '/usr/local/bin' && rm -f ocserv-fw
    cd '/usr/local/sbin' && rm -f ocserv
    cd '/usr/local/share/man/man8' && rm -f ocserv.8
    rm -f ocpasswd.8
    rm -f occtl.8
    echo && echo "安装过程错误,ocserv 卸载完成 !" && echo
}
Add_iptables(){
    iptables -I INPUT -m state --state NEW -m tcp -p tcp --dport ${set_tcp_port} -j ACCEPT
    iptables -I INPUT -m state --state NEW -m udp -p udp --dport ${set_udp_port} -j ACCEPT
}
Del_iptables(){
    iptables -D INPUT -m state --state NEW -m tcp -p tcp --dport ${tcp_port} -j ACCEPT
    iptables -D INPUT -m state --state NEW -m udp -p udp --dport ${udp_port} -j ACCEPT
}
Save_iptables(){
    iptables-save > /etc/iptables.up.rules
}
Set_iptables(){
    echo -e "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
    sysctl -p
    ifconfig_status=$(ifconfig)
    if [[ -z ${ifconfig_status} ]]; then
        echo -e "${Error} ifconfig 未安装 !"
        read -e -p "请手动输入你的网卡名(一般情况下,网卡名为 eth0,Debian9 则为 ens3,CentOS Ubuntu 最新版本可能为 enpXsX(X代表数字或字母),OpenVZ 虚拟化则为 venet0):" Network_card
        [[ -z "${Network_card}" ]] && echo "取消..." && exit 1
    else
        Network_card=$(ifconfig|grep "eth0")
        if [[ ! -z ${Network_card} ]]; then
            Network_card="eth0"
        else
            Network_card=$(ifconfig|grep "ens3")
            if [[ ! -z ${Network_card} ]]; then
                Network_card="ens3"
            else
                Network_card=$(ifconfig|grep "venet0")
                if [[ ! -z ${Network_card} ]]; then
                    Network_card="venet0"
                else
                    ifconfig
                    read -e -p "检测到本服务器的网卡非 eth0 \ ens3(Debian9) \ venet0(OpenVZ) \ enpXsX(CentOS Ubuntu 最新版本,X代表数字或字母),请根据上面输出的网卡信息手动输入你的网卡名:" Network_card
                    [[ -z "${Network_card}" ]] && echo "取消..." && exit 1
                fi
            fi
        fi
    fi
    iptables -t nat -A POSTROUTING -o ${Network_card} -j MASQUERADE
    
    iptables-save > /etc/iptables.up.rules
    echo -e '#!/bin/bash\n/sbin/iptables-restore < /etc/iptables.up.rules' > /etc/network/if-pre-up.d/iptables
    chmod +x /etc/network/if-pre-up.d/iptables
}

Enable_2FA(){
    check_root
    check_installed_status
    local helper="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/ocserv-2fa-user.py"
    [[ -f "$helper" ]] || { echo "请将 ocserv-2fa-user.py 放在本脚本同一目录"; return 1; }
    "${file}" --version 2>&1 | grep -qi oath || { echo "当前 ocserv 未编译 OATH 支持,需要先以 liboath-dev 重新编译;不要直接重装已有服务器。"; return 1; }
    grep -qE '^auth[[:space:]]*=[[:space:]]*"plain\[passwd=/etc/ocserv/ocpasswd(,otp=/etc/ocserv/users.oath)?\]"[[:space:]]*$' "$conf" || { echo "认证配置不是预期的 ocpasswd 配置,请手动检查。"; return 1; }
    [[ $(grep -Ec '^[[:space:]]*(auth|enable-auth)[[:space:]]*=' "$conf") == 1 ]] || { echo "存在其他认证入口,请先检查。"; return 1; }
    local account group hash
    while IFS=: read -r account group hash; do
        [[ -z "$account" || -z "$hash" || "$hash" == '!'* || "$hash" == '*'* ]] && continue
        python3 "$helper" "$account" || return 1
    done < "$passwd_file"
    local backup="${conf}.pre-2fa.$(date +%Y%m%d%H%M%S)"
    cp -p "$conf" "$backup" || return 1
    sed -i 's|^auth[[:space:]]*=.*|auth = "plain[passwd=/etc/ocserv/ocpasswd,otp=/etc/ocserv/users.oath]"|' "$conf"
    if ! "$file" -t -c "$conf"; then cp -p "$backup" "$conf"; echo "配置检查失败,已恢复"; return 1; fi
    echo "请保存以上绑定密钥,在 Google Authenticator 中按时间添加。即将重启 VPN 服务。"
    Restart_ocserv
}

Update_Shell(){
    echo "此版本包含双重认证修改,请勿使用上游脚本覆盖。"
}

check_sys
[[ ${release} != "debian" ]] && [[ ${release} != "ubuntu" ]] && echo -e "${Error} 本脚本不支持当前系统 ${release} !" && exit 1
echo && echo -e " ocserv 管理脚本 ${Red_font_prefix}[v${sh_ver}]${Font_color_suffix}
  
 ${Green_font_prefix}0.${Font_color_suffix} 升级脚本
————————————
 ${Green_font_prefix}1.${Font_color_suffix} 安装 ocserv
 ${Green_font_prefix}2.${Font_color_suffix} 卸载 ocserv
————————————
 ${Green_font_prefix}3.${Font_color_suffix} 启动 ocserv
 ${Green_font_prefix}4.${Font_color_suffix} 停止 ocserv
 ${Green_font_prefix}5.${Font_color_suffix} 重启 ocserv
————————————
 ${Green_font_prefix}6.${Font_color_suffix} 设置 账号配置
 ${Green_font_prefix}7.${Font_color_suffix} 查看 配置信息
 ${Green_font_prefix}8.${Font_color_suffix} 修改 配置文件
 ${Green_font_prefix}9.${Font_color_suffix} 查看 日志信息
 ${Green_font_prefix}10.${Font_color_suffix} 开启/查看 Google Authenticator 绑定
————————————" && echo
if [[ -e ${file} ]]; then
    check_pid
    if [[ ! -z "${PID}" ]]; then
        echo -e " 当前状态: ${Green_font_prefix}已安装${Font_color_suffix} 并 ${Green_font_prefix}已启动${Font_color_suffix}"
    else
        echo -e " 当前状态: ${Green_font_prefix}已安装${Font_color_suffix} 但 ${Red_font_prefix}未启动${Font_color_suffix}"
    fi
else
    echo -e " 当前状态: ${Red_font_prefix}未安装${Font_color_suffix}"
fi
echo
read -e -p " 请输入数字 [0-10]:" num
case "$num" in
    0)
    Update_Shell
    ;;
    1)
    Install_ocserv
    ;;
    2)
    Uninstall_ocserv
    ;;
    3)
    Start_ocserv
    ;;
    4)
    Stop_ocserv
    ;;
    5)
    Restart_ocserv
    ;;
    6)
    Set_Pass
    ;;
    7)
    View_Config
    ;;
    8)
    Set_ocserv
    ;;
    9)
    View_Log
    ;;
    10)
    Enable_2FA
    ;;
    *)
    echo "请输入正确数字 [0-10]"
    ;;
esac
Last modification:October 25, 2026
如果觉得我的文章对你有用,请随意赞赏