生成证书脚本


create_crt.py

# coding=utf-8

import os
from os.path import join as path_join  #join 使用指定的连接符,连接字符串
key_dir = '/etc/openvpn/keys'
name_key = '/etc/openvpn/easy-rsa/3/pki/private'
name_crt = '/etc/openvpn/easy-rsa/3/pki/issued'
ovpn_dir = '/etc/openvpn/open_keys/keys/'
def read_file(p):                #读文件
    with open(p) as f:          #打开文件,赋值给f
        return f.read()          #读取

def write_file(p, c):              #写文件
    with open(p, 'w') as f:
        f.write(c)              #打开p,写入c

def gen_config(template, ca, n):
    # print key_dir, n, len(template), len(ca)
    key = read_file(path_join(name_key, n + '.key'))
    crt = read_file(path_join(name_crt, n + '.crt'))
    # ca 替换掉%%CA%%
    config = template. \
            replace('%%CA%%', ca). \
            replace('%%CERT%%', crt). \
            replace('%%KEY%%', key)
    write_file(ovpn_dir+n+'.ovpn', config)

def _main(_, template_file, *names):
    assert template_file   #断言判断是否存在,等价if not  template_file: raise AssertionError
    template = read_file(template_file)       #读取模板文件
    ca = read_file(path_join(key_dir, 'ca.crt'))   #读取ca.crt文件
    for n in names:           #创建用户证书
        os.system('./user.sh %s' % n)
        print ('创建了 %s 的用户证书' % n)
        gen_config(template, ca,  n)

def main():
    import sys
    if len(sys.argv) < 3:        #sys.argv 获取命名行参数,最少要有2个参数,模板文件和用户名,用户名可以有多个。
        print ('Usage: %s <config_template>  <name1> [<name2> ...]' % sys.argv[0])
    else:
        _main(*sys.argv)

if __name__ == '__main__':
    main()

user.sh

#! /bin/bash
EASY_RSA_DIR=/etc/openvpn/easy-rsa/3/
PKI_DIR=$EASY_RSA_DIR/$EASY_RSA_VERSION/pki
for user in "$@"
do
   cd $EASY_RSA_DIR
  ./easyrsa build-client-full $user nopass
done

使用方法

python3.6  create_crt.py  template_file  用户名1  用户名2 ..... 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值