centos7.6 一键安装 openvpn的shell脚本

#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!"

使用方法

  1. 将上述脚本保存为一个文件,例如 install_openvpn.sh
  2. 通过运行 chmod +x install_openvpn.sh 命令使脚本可执行。
  3. 以root用户身份执行脚本:./install_openvpn.sh

注意事项

  • 在生产环境中运行脚本前,请确保您已经了解脚本的内容并对其进行了适当的审查和测试。
  • 此脚本没有设置OpenVPN服务器的配置文件,您可能需要根据您的网络环境调整 /etc/openvpn/server.conf 文件。
  • 安全性至关重要,所以在生成证书时考虑使用强密码,并在生产环境中移除 nopass 选项以保证证书的安全。
  • 如果您的服务器有防火墙或SELinux启用,可能需要额外的步骤来确保OpenVPN可以正常工作。

添加用户

shell添加用户

在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_IPYOUR_SERVER_PORT为你的OpenVPN服务器的IP地址和端口。
  • easy-rsa目录位于/etc/openvpn/easy-rsa,如果不是,请修改脚本中的相应路径。
  • 你有足够的权限执行这个脚本,通常需要root权限。
  • 这个脚本假设OpenVPN已经安装和配置好,且easy-rsavars文件也已经设置好。
  • 在生成客户端配置文件时,<ca>, <cert>, <key>, 和 <tls-auth>部分会插入相应的证书和密钥内容。确保这些内容的路径和你的系统设置一致。
  • 为了安全起见,你可能想要在生成客户端证书时不使用nopass参数,而是为每个客户端证书设置一个密码。

在生产环境中使用这个脚本之前,请彻底测试确保它符合你的需求,并且在安全的环境中运行。

python添加用户

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代码之前,请确保:

  1. 你有合适的权限,通常需要root权限来生成证书和密钥。
  2. easy-rsa 已经安装在指定的路径上,且正确配置。
  3. Python环境已经设置完毕,可以运行上述脚本。

这段代码中没有包括OpenVPN服务器的配置文件更新,这通常是在生成客户端证书和密钥之后需要进行的步骤。您需要根据实际情况调整和完善这个脚本,以满足您的具体需求。在生产环境中使用之前,请确保进行了彻底的测试。

go添加用户

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代码需要满足以下条件:

  1. 你的Go环境已经设置并且可以运行Go代码。
  2. 你的用户有足够的权限执行easy-rsa脚本,这通常意味着需要以root权限运行Go程序。
  3. 确保easy-rsa路径在Go脚本中设置正确,并且easy-rsa已经按照OpenVPN的要求配置。

这段代码没有处理所有可能的错误情况,因此在生产环境中使用前应添加额外的错误处理和验证步骤。此外,实际使用时可能还需要其他配置步骤,比如设置OpenVPN服务器以识别新证书,以及为客户端生成配置文件。

nodejs添加用户

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');
  1. 这个脚本需要Node.js环境。
  2. 在执行之前,确保你的Node.js脚本有足够的权限来运行easy-rsa命令。
  3. 确保你已经安装并配置了easy-rsa,并且脚本中的路径是正确的。
  4. 这段代码不包括错误处理逻辑,实际使用时你可能需要添加更完善的错误处理。
  5. 生成的证书和密钥文件路径在脚本输出中显示,你需要根据实际情况来决定如何使用这些文件。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值