当前位置:   article > 正文

centos7.6 一键安装 openvpn的shell脚本_centos 一键安装脚本怎么写

centos 一键安装脚本怎么写

#openvpn一键安装脚本#

最近有家庭和单位组网需要,研究了一整openvpn的搭建以及添加用户,以下代码分别写了go,shell,python,nodejs添加vpn用户的方法,方便集成到动态程序里面使用

安装脚本

下面是一个简单的CentOS 7.6上一键安装OpenVPN的Shell脚本示例。请注意,在运行此脚本之前,确保您有相应的权限,并且已经对系统进行了备份。

  1. #!/bin/bash
  2. # One-Click OpenVPN Install Script for CentOS 7.6
  3. # Ensure the script is run as root
  4. if [ "$EUID" -ne 0 ]
  5. then echo "Please run as root"
  6. exit
  7. fi
  8. # Update the system
  9. yum update -y
  10. # Install EPEL repository
  11. yum install -y epel-release
  12. # Install OpenVPN and easy-rsa for generating SSL certificates
  13. yum install -y openvpn easy-rsa
  14. # Copy the sample server.conf to /etc/openvpn
  15. cp /usr/share/doc/openvpn-*/sample/sample-config-files/server.conf /etc/openvpn/
  16. # Set up the CA directory
  17. mkdir -p /etc/openvpn/easy-rsa/keys
  18. cp -ai /usr/share/easy-rsa/3.*/ /etc/openvpn/easy-rsa
  19. cd /etc/openvpn/easy-rsa/
  20. # Initialize the PKI
  21. ./easyrsa init-pki
  22. # Build the CA
  23. ./easyrsa build-ca nopass
  24. # Generate the server certificate
  25. ./easyrsa build-server-full server nopass
  26. # Generate the Diffie-Hellman parameters
  27. ./easyrsa gen-dh
  28. # Generate the HMAC signature to strengthen the server's TLS integrity verification capabilities
  29. openvpn --genkey --secret ta.key
  30. # Copy the generated certificates and keys
  31. cp pki/ca.crt pki/private/ca.key pki/issued/server.crt pki/private/server.key pki/dh.pem /etc/openvpn/
  32. # Copy the ta.key to the /etc/openvpn directory
  33. cp ta.key /etc/openvpn/
  34. # Enable and start the OpenVPN service
  35. systemctl enable openvpn@server.service
  36. systemctl start openvpn@server.service
  37. # Add firewall rules to allow traffic on the OpenVPN tunnel interface
  38. firewall-cmd --permanent --add-service=openvpn
  39. firewall-cmd --permanent --add-masquerade
  40. firewall-cmd --reload
  41. # Add server to auto start on boot
  42. chkconfig openvpn on
  43. 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来创建客户端证书和密钥。以下是一个示例脚本,展示了如何为一个新用户生成必要的证书和配置文件。

  1. #!/bin/bash
  2. # This script assumes that easy-rsa is already installed and configured
  3. # at /etc/openvpn/easy-rsa for your OpenVPN setup.
  4. # Function to add a new OpenVPN user
  5. add_openvpn_user() {
  6. local username="$1"
  7. local EASY_RSA="/etc/openvpn/easy-rsa"
  8. local PKI_DIR="$EASY_RSA/pki"
  9. # Check if the client's name is passed
  10. if [[ -z "$username" ]]; then
  11. echo "You must provide a username for the client."
  12. exit 1
  13. fi
  14. # Navigate to the easy-rsa directory to initialize the environment
  15. cd "$EASY_RSA" || exit
  16. # Source vars settings
  17. if [[ -f vars ]]; then
  18. source vars
  19. else
  20. echo "The vars file could not be found at $EASY_RSA/vars."
  21. exit 1
  22. fi
  23. # Build the client certificate without a passphrase
  24. ./easyrsa build-client-full "$username" nopass
  25. # Ensure the certificate was created
  26. if [[ ! -f "$PKI_DIR/issued/$username.crt" ]]; then
  27. echo "The certificate for $username was not created."
  28. exit 1
  29. else
  30. echo "Certificate for user $username generated successfully."
  31. fi
  32. # Generate the client config file
  33. cat > "$PKI_DIR/$username.ovpn" <<EOF
  34. client
  35. dev tun
  36. proto udp
  37. remote YOUR_SERVER_IP YOUR_SERVER_PORT
  38. resolv-retry infinite
  39. nobind
  40. persist-key
  41. persist-tun
  42. remote-cert-tls server
  43. cipher AES-256-CBC
  44. auth SHA256
  45. key-direction 1
  46. verb 3
  47. <ca>
  48. $(cat "$PKI_DIR/ca.crt")
  49. </ca>
  50. <cert>
  51. $(awk '/BEGIN/,/END/' < "$PKI_DIR/issued/$username.crt")
  52. </cert>
  53. <key>
  54. $(cat "$PKI_DIR/private/$username.key")
  55. </key>
  56. <tls-auth>
  57. $(cat "$PKI_DIR/ta.key")
  58. </tls-auth>
  59. EOF
  60. echo "Client configuration file created at $PKI_DIR/$username.ovpn"
  61. }
  62. # Replace 'newclient' with the desired username
  63. 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用户的示例代码。

  1. import subprocess
  2. import os
  3. # Set the path to the easy-rsa directory
  4. EASY_RSA_PATH = '/etc/openvpn/easy-rsa'
  5. PKI_PATH = os.path.join(EASY_RSA_PATH, 'pki')
  6. def add_openvpn_user(username):
  7. # Navigate to the easy-rsa directory to initialize the environment
  8. os.chdir(EASY_RSA_PATH)
  9. # Build the client certificate without a passphrase
  10. build_client_full_cmd = ['./easyrsa', 'build-client-full', username, 'nopass']
  11. try:
  12. subprocess.check_output(build_client_full_cmd, stderr=subprocess.STDOUT)
  13. print(f"Certificate for user {username} generated successfully.")
  14. # Define the paths for the new user's certificate and key
  15. user_cert = os.path.join(PKI_PATH, 'issued', f'{username}.crt')
  16. user_key = os.path.join(PKI_PATH, 'private', f'{username}.key')
  17. # Output the generated client certificate and key file paths
  18. print(f"User Certificate: {user_cert}")
  19. print(f"User Key: {user_key}")
  20. # You may also want to copy the cert and key to the client configuration directory
  21. # and create a client config file if necessary.
  22. except subprocess.CalledProcessError as e:
  23. print(f"An error occurred while generating the certificate for user {username}: {e.output.decode()}")
  24. # Replace 'newusername' with the desired username
  25. add_openvpn_user('newusername')

在执行这段Python代码之前,请确保:

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

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

go添加用户

Go中为OpenVPN添加用户通常涉及到使用exec包来运行shell命令,这与在Node.js中使用child_process模块类似。下面是一个Go语言的示例,它生成一个新的OpenVPN用户的客户端证书

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "os/exec"
  6. "path/filepath"
  7. )
  8. // AddOpenVPNUser creates a new client certificate for a user
  9. func AddOpenVPNUser(username string) error {
  10. easyRsaPath := "/etc/openvpn/easy-rsa" // Replace with your easy-rsa path
  11. pkiPath := filepath.Join(easyRsaPath, "pki")
  12. // The 'source' command is not available in the exec package,
  13. // so we run commands directly with the environment set.
  14. cmd := exec.Command(filepath.Join(easyRsaPath, "easyrsa"), "build-client-full", username, "nopass")
  15. cmd.Dir = easyRsaPath
  16. output, err := cmd.CombinedOutput()
  17. if err != nil {
  18. return fmt.Errorf("error generating certificate for user %s: %s\n%s", username, err, output)
  19. }
  20. fmt.Printf("Certificate for user %s generated successfully.\n", username)
  21. // Display the generated certificate and key file paths
  22. userCertPath := filepath.Join(pkiPath, "issued", fmt.Sprintf("%s.crt", username))
  23. userKeyPath := filepath.Join(pkiPath, "private", fmt.Sprintf("%s.key", username))
  24. fmt.Printf("User Certificate: %s\n", userCertPath)
  25. fmt.Printf("User Key: %s\n", userKeyPath)
  26. // Further actions can be taken here, such as copying the certificate
  27. // and key to appropriate directories or incorporating them into OpenVPN
  28. // server configurations.
  29. return nil
  30. }
  31. func main() {
  32. username := "newuser" // Replace with the username to add
  33. err := AddOpenVPNUser(username)
  34. if err != nil {
  35. log.Fatal(err)
  36. }
  37. }

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

  1. const { exec } = require('child_process');
  2. const path = require('path');
  3. // Function to add a new OpenVPN user
  4. function addOpenVPNUser(username) {
  5. // Define the easy-rsa directory (update this to your easy-rsa path)
  6. const easyRsaPath = '/etc/openvpn/easy-rsa';
  7. const pkiPath = path.join(easyRsaPath, 'pki');
  8. // Change to the easy-rsa directory to initialize the environment
  9. process.chdir(easyRsaPath);
  10. // Build the client certificate without a passphrase
  11. exec(`./easyrsa build-client-full ${username} nopass`, (error, stdout, stderr) => {
  12. if (error) {
  13. console.error(`Error generating certificate for user ${username}: ${error}`);
  14. return;
  15. }
  16. console.log(`Certificate for user ${username} generated successfully.`);
  17. console.log(stdout);
  18. // Output the generated client certificate and key files
  19. const userCertPath = path.join(pkiPath, 'issued', `${username}.crt`);
  20. const userKeyPath = path.join(pkiPath, 'private', `${username}.key`);
  21. console.log(`User Certificate: ${userCertPath}`);
  22. console.log(`User Key: ${userKeyPath}`);
  23. // Here you can proceed to add these paths to your OpenVPN server configuration
  24. // or generate a client config file to distribute to the user.
  25. });
  26. }
  27. // Usage: Replace 'newuser' with the desired username
  28. addOpenVPNUser('newuser');
  1. 这个脚本需要Node.js环境。
  2. 在执行之前,确保你的Node.js脚本有足够的权限来运行easy-rsa命令。
  3. 确保你已经安装并配置了easy-rsa,并且脚本中的路径是正确的。
  4. 这段代码不包括错误处理逻辑,实际使用时你可能需要添加更完善的错误处理。
  5. 生成的证书和密钥文件路径在脚本输出中显示,你需要根据实际情况来决定如何使用这些文件。
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/202935
推荐阅读
相关标签
  

闽ICP备14008679号