赞
踩
#openvpn一键安装脚本#
最近有家庭和单位组网需要,研究了一整openvpn的搭建以及添加用户,以下代码分别写了go,shell,python,nodejs添加vpn用户的方法,方便集成到动态程序里面使用
下面是一个简单的CentOS 7.6上一键安装OpenVPN的Shell脚本示例。请注意,在运行此脚本之前,确保您有相应的权限,并且已经对系统进行了备份。
- #!/bin/bash
- # One-Click OpenVPN Install Script for CentOS 7.6
-
- # Ensure the script is run as root
- if [ "$EUID" -ne 0 ]
- then echo "Please run as root"
- exit
- fi
-
- # Update the system
- yum update -y
-
- # Install EPEL repository
- yum install -y epel-release
-
- # Install OpenVPN and easy-rsa for generating SSL certificates
- yum install -y openvpn easy-rsa
-
- # Copy the sample server.conf to /etc/openvpn
- cp /usr/share/doc/openvpn-*/sample/sample-config-files/server.conf /etc/openvpn/
-
- # Set up the CA directory
- mkdir -p /etc/openvpn/easy-rsa/keys
- cp -ai /usr/share/easy-rsa/3.*/ /etc/openvpn/easy-rsa
- cd /etc/openvpn/easy-rsa/
-
- # Initialize the PKI
- ./easyrsa init-pki
-
- # Build the CA
- ./easyrsa build-ca nopass
-
- # Generate the server certificate
- ./easyrsa build-server-full server nopass
-
- # Generate the Diffie-Hellman parameters
- ./easyrsa gen-dh
-
- # Generate the HMAC signature to strengthen the server's TLS integrity verification capabilities
- openvpn --genkey --secret ta.key
-
- # Copy the generated certificates and keys
- cp pki/ca.crt pki/private/ca.key pki/issued/server.crt pki/private/server.key pki/dh.pem /etc/openvpn/
-
- # Copy the ta.key to the /etc/openvpn directory
- cp ta.key /etc/openvpn/
-
- # Enable and start the OpenVPN service
- systemctl enable openvpn@server.service
- systemctl start openvpn@server.service
-
- # Add firewall rules to allow traffic on the OpenVPN tunnel interface
- firewall-cmd --permanent --add-service=openvpn
- firewall-cmd --permanent --add-masquerade
- firewall-cmd --reload
-
- # Add server to auto start on boot
- chkconfig openvpn on
-
- echo "OpenVPN installation is complete!"

使用方法:
install_openvpn.sh
。chmod +x install_openvpn.sh
命令使脚本可执行。./install_openvpn.sh
。注意事项:
/etc/openvpn/server.conf
文件。nopass
选项以保证证书的安全。在Shell脚本中为OpenVPN添加一个新用户通常涉及到使用easy-rsa
来创建客户端证书和密钥。以下是一个示例脚本,展示了如何为一个新用户生成必要的证书和配置文件。
- #!/bin/bash
-
- # This script assumes that easy-rsa is already installed and configured
- # at /etc/openvpn/easy-rsa for your OpenVPN setup.
-
- # Function to add a new OpenVPN user
- add_openvpn_user() {
- local username="$1"
- local EASY_RSA="/etc/openvpn/easy-rsa"
- local PKI_DIR="$EASY_RSA/pki"
-
- # Check if the client's name is passed
- if [[ -z "$username" ]]; then
- echo "You must provide a username for the client."
- exit 1
- fi
-
- # Navigate to the easy-rsa directory to initialize the environment
- cd "$EASY_RSA" || exit
-
- # Source vars settings
- if [[ -f vars ]]; then
- source vars
- else
- echo "The vars file could not be found at $EASY_RSA/vars."
- exit 1
- fi
-
- # Build the client certificate without a passphrase
- ./easyrsa build-client-full "$username" nopass
-
- # Ensure the certificate was created
- if [[ ! -f "$PKI_DIR/issued/$username.crt" ]]; then
- echo "The certificate for $username was not created."
- exit 1
- else
- echo "Certificate for user $username generated successfully."
- fi
-
- # Generate the client config file
- cat > "$PKI_DIR/$username.ovpn" <<EOF
- client
- dev tun
- proto udp
- remote YOUR_SERVER_IP YOUR_SERVER_PORT
- resolv-retry infinite
- nobind
- persist-key
- persist-tun
- remote-cert-tls server
- cipher AES-256-CBC
- auth SHA256
- key-direction 1
- verb 3
- <ca>
- $(cat "$PKI_DIR/ca.crt")
- </ca>
- <cert>
- $(awk '/BEGIN/,/END/' < "$PKI_DIR/issued/$username.crt")
- </cert>
- <key>
- $(cat "$PKI_DIR/private/$username.key")
- </key>
- <tls-auth>
- $(cat "$PKI_DIR/ta.key")
- </tls-auth>
- EOF
-
- echo "Client configuration file created at $PKI_DIR/$username.ovpn"
- }
-
- # Replace 'newclient' with the desired username
- add_openvpn_user "newclient"

在使用这个脚本之前,请确保:
YOUR_SERVER_IP
和YOUR_SERVER_PORT
为你的OpenVPN服务器的IP地址和端口。easy-rsa
目录位于/etc/openvpn/easy-rsa
,如果不是,请修改脚本中的相应路径。easy-rsa
的vars
文件也已经设置好。<ca>
, <cert>
, <key>
, 和 <tls-auth>
部分会插入相应的证书和密钥内容。确保这些内容的路径和你的系统设置一致。nopass
参数,而是为每个客户端证书设置一个密码。在生产环境中使用这个脚本之前,请彻底测试确保它符合你的需求,并且在安全的环境中运行。
Python中创建OpenVPN用户通常涉及到调用外部命令以运行easy-rsa
脚本来生成相应的客户端证书和密钥。以下是一个使用Python subprocess
模块来添加OpenVPN用户的示例代码。
- import subprocess
- import os
-
- # Set the path to the easy-rsa directory
- EASY_RSA_PATH = '/etc/openvpn/easy-rsa'
- PKI_PATH = os.path.join(EASY_RSA_PATH, 'pki')
-
- def add_openvpn_user(username):
- # Navigate to the easy-rsa directory to initialize the environment
- os.chdir(EASY_RSA_PATH)
-
- # Build the client certificate without a passphrase
- build_client_full_cmd = ['./easyrsa', 'build-client-full', username, 'nopass']
-
- try:
- subprocess.check_output(build_client_full_cmd, stderr=subprocess.STDOUT)
- print(f"Certificate for user {username} generated successfully.")
-
- # Define the paths for the new user's certificate and key
- user_cert = os.path.join(PKI_PATH, 'issued', f'{username}.crt')
- user_key = os.path.join(PKI_PATH, 'private', f'{username}.key')
-
- # Output the generated client certificate and key file paths
- print(f"User Certificate: {user_cert}")
- print(f"User Key: {user_key}")
-
- # You may also want to copy the cert and key to the client configuration directory
- # and create a client config file if necessary.
-
- except subprocess.CalledProcessError as e:
- print(f"An error occurred while generating the certificate for user {username}: {e.output.decode()}")
-
- # Replace 'newusername' with the desired username
- add_openvpn_user('newusername')

在执行这段Python代码之前,请确保:
easy-rsa
已经安装在指定的路径上,且正确配置。这段代码中没有包括OpenVPN服务器的配置文件更新,这通常是在生成客户端证书和密钥之后需要进行的步骤。您需要根据实际情况调整和完善这个脚本,以满足您的具体需求。在生产环境中使用之前,请确保进行了彻底的测试。
Go中为OpenVPN添加用户通常涉及到使用exec
包来运行shell命令,这与在Node.js中使用child_process
模块类似。下面是一个Go语言的示例,它生成一个新的OpenVPN用户的客户端证书
- package main
-
- import (
- "fmt"
- "log"
- "os/exec"
- "path/filepath"
- )
-
- // AddOpenVPNUser creates a new client certificate for a user
- func AddOpenVPNUser(username string) error {
- easyRsaPath := "/etc/openvpn/easy-rsa" // Replace with your easy-rsa path
- pkiPath := filepath.Join(easyRsaPath, "pki")
-
- // The 'source' command is not available in the exec package,
- // so we run commands directly with the environment set.
- cmd := exec.Command(filepath.Join(easyRsaPath, "easyrsa"), "build-client-full", username, "nopass")
- cmd.Dir = easyRsaPath
-
- output, err := cmd.CombinedOutput()
- if err != nil {
- return fmt.Errorf("error generating certificate for user %s: %s\n%s", username, err, output)
- }
-
- fmt.Printf("Certificate for user %s generated successfully.\n", username)
-
- // Display the generated certificate and key file paths
- userCertPath := filepath.Join(pkiPath, "issued", fmt.Sprintf("%s.crt", username))
- userKeyPath := filepath.Join(pkiPath, "private", fmt.Sprintf("%s.key", username))
-
- fmt.Printf("User Certificate: %s\n", userCertPath)
- fmt.Printf("User Key: %s\n", userKeyPath)
-
- // Further actions can be taken here, such as copying the certificate
- // and key to appropriate directories or incorporating them into OpenVPN
- // server configurations.
-
- return nil
- }
-
- func main() {
- username := "newuser" // Replace with the username to add
-
- err := AddOpenVPNUser(username)
- if err != nil {
- log.Fatal(err)
- }
- }

Go代码需要满足以下条件:
easy-rsa
脚本,这通常意味着需要以root权限运行Go程序。easy-rsa
路径在Go脚本中设置正确,并且easy-rsa
已经按照OpenVPN的要求配置。这段代码没有处理所有可能的错误情况,因此在生产环境中使用前应添加额外的错误处理和验证步骤。此外,实际使用时可能还需要其他配置步骤,比如设置OpenVPN服务器以识别新证书,以及为客户端生成配置文件。
Node.js中添加OpenVPN用户通常涉及到生成唯一的客户端证书。下面的代码示例使用了child_process
模块来调用OpenVPN的easy-rsa
脚本生成证书,并且假设您已经按照OpenVPN的标准方式设置了easy-rsa
。
- const { exec } = require('child_process');
- const path = require('path');
-
- // Function to add a new OpenVPN user
- function addOpenVPNUser(username) {
- // Define the easy-rsa directory (update this to your easy-rsa path)
- const easyRsaPath = '/etc/openvpn/easy-rsa';
- const pkiPath = path.join(easyRsaPath, 'pki');
-
- // Change to the easy-rsa directory to initialize the environment
- process.chdir(easyRsaPath);
-
- // Build the client certificate without a passphrase
- exec(`./easyrsa build-client-full ${username} nopass`, (error, stdout, stderr) => {
- if (error) {
- console.error(`Error generating certificate for user ${username}: ${error}`);
- return;
- }
-
- console.log(`Certificate for user ${username} generated successfully.`);
- console.log(stdout);
-
- // Output the generated client certificate and key files
- const userCertPath = path.join(pkiPath, 'issued', `${username}.crt`);
- const userKeyPath = path.join(pkiPath, 'private', `${username}.key`);
-
- console.log(`User Certificate: ${userCertPath}`);
- console.log(`User Key: ${userKeyPath}`);
-
- // Here you can proceed to add these paths to your OpenVPN server configuration
- // or generate a client config file to distribute to the user.
- });
- }
-
- // Usage: Replace 'newuser' with the desired username
- addOpenVPNUser('newuser');

easy-rsa
命令。easy-rsa
,并且脚本中的路径是正确的。Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。