大网数据广告活动
服务器运维问答

OpenVPN adding static ip for client dynamically based on a script

· 52CE 我爱测

In my VPN logic all of my client certificates have the folowing CN template: number.mycompany.com where number is between 2-65536 For each CN I add a config file which looks like so: $ cat 65501.mycompany.com ifconfig-push 10.22.…

问题原文

原帖链接 · ofirule · CC BY-SA 4.0

In my VPN logic all of my client certificates have the folowing CN template:

number.mycompany.com where number is between 2-65536

For each CN I add a config file which looks like so:

$ cat 65501.mycompany.com
ifconfig-push 10.22.255.221 255.255.0.0

So basically based on the CN number area I configure the static ip in the relevant file, conversion from number to ip logic:

$ python3 -c "print('10.22.{}.{}'.format(*divmod(65501, 256)))"
10.22.255.221

Is there a way to do it dynamically in the config with a script or something else, instead of adding client config file everytime?

已采纳解答

原帖链接 · ofirule · CC BY-SA 4.0

Reading the manuall carefully I saw it's possible to add a script with the ability to dynamically change the config per client using the --client-connect flag.

I added the following config line to my server.conf file:

client-connect /etc/openvpn/client_set_static_ip.sh

and the file content is the following bash script:

#!/usr/bin/env bash

DYNAMIC_GENERATED_CONFIG_PATH=$1

function get_client_num() {
  # returns the client number from the `common_name` env variable
  local cn_arr=(${common_name//./ })
  local cn_arr_first=${cn_arr[0]}
  echo "${cn_arr_first}"
}

function generate_client_ip() {
  # returns generated remote client ip from the `ifconfig_pool_remote_ip` env variable and client_num
  local ifconfig_remote_arr=(${ifconfig_pool_remote_ip//./ })

  local client_num=$(get_client_num)
  local remote_ip_octet_1=${ifconfig_remote_arr[0]}
  local remote_ip_octet_2=${ifconfig_remote_arr[1]}
  local remote_ip_octet_3=$((client_num/256))
  local remote_ip_octet_4=$((client_num%256))

  echo "${remote_ip_octet_1}.${remote_ip_octet_2}.${remote_ip_octet_3}.${remote_ip_octet_4}"
}

  remote_ip=$(generate_client_ip)
  echo "ifconfig-push ${remote_ip} 255.255.0.0" > "${DYNAMIC_GENERATED_CONFIG_PATH}"

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2022-05-31)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。