Skip to content

Instantly share code, notes, and snippets.

@anviar
Last active May 14, 2018 11:15
Show Gist options
  • Save anviar/4717b1599dd59e7567909729d5ab3ae8 to your computer and use it in GitHub Desktop.
Save anviar/4717b1599dd59e7567909729d5ab3ae8 to your computer and use it in GitHub Desktop.
SSL request automation
# -*- coding: utf-8 -*-
import os
from argparse import ArgumentParser, ArgumentTypeError
import subprocess
from string import Template
import re
from platform import system
import pyperclip
from time import ctime
runtime_env = os.environ.copy()
if system() == 'Windows':
import urllib.request
import json
openssl_cmd = 'C:\\OpenSSL\\bin\\openssl.exe'
with urllib.request.urlopen('https://slproweb.com/download/win32_openssl_hashes.json') as response:
releases = json.loads(response.read())
basever = ''
for f in releases['files']:
if releases['files'][f]['bits'] == 64 and 'Light' in f:
ver = '{}{}'.format(
releases['files'][f]['basever'],
releases['files'][f]['subver'])
if basever < ver:
basever = ver
dl_url = releases['files'][f]['url']
if not os.path.isfile(openssl_cmd):
print(u'OpenSSL не найден по пути: ' + openssl_cmd)
print(u'Скачать: ' + dl_url)
exit(1)
else:
cver = subprocess.run([openssl_cmd, 'version'],
env=runtime_env,
check=True,
stdout=subprocess.PIPE).stdout.decode().strip().split()[1]
if cver < basever:
print(u'Обнаружено обновление: ' + dl_url)
else:
openssl_cmd = 'openssl'
def valid_domain(input_domain):
if not re.match(r'''^((?=[a-z0-9-]{1,63}\.)
(
[a-z0-9]+
|[a-z0-9][a-z0-9-]*[a-z0-9])*\.
)+([a-z]|xn--[a-z0-9-]+){2,63}$''',
input_domain.replace('*.', ''), re.VERBOSE):
raise ArgumentTypeError('Неправильный ввод домена %s')
return input_domain
parser = ArgumentParser(description=u'Сгенерировать запрос сертификата')
parser.add_argument('-d', '--domain', help=u'имя домена',
type=valid_domain, required=True)
args = parser.parse_args()
# Environment
workdir = os.path.dirname(os.path.realpath(__file__))
output_dir = os.path.join(workdir, args.domain.replace('*', '#'))
key_path = os.path.join(output_dir,
args.domain.replace('.', '_').replace('*', '#') + '.key')
request_path = os.path.join(output_dir,
args.domain.replace('.', '_').replace('*', '#') + '.csr')
if not os.path.isdir(output_dir):
os.mkdir(output_dir)
# generate config from template
with open(os.path.join(workdir, 'openssl.template'), 'rt') as template_file:
config_template = Template(template_file.read())
template_values = {
'HOME': output_dir,
'default_keyfile': key_path,
'commonName': args.domain
}
with open(os.path.join(output_dir, 'openssl.cnf'), 'wt') as config_file:
config_file.write(config_template.substitute(template_values))
# ======================================
if not os.path.isfile(key_path):
print(u">>> генерация секретного ключа")
cmd = [openssl_cmd, 'genrsa', '-out', key_path]
subprocess.run(cmd, env=runtime_env, check=True)
else:
print(u">>> Используем существующий секретный ключ ({})".format(ctime(os.path.getmtime(key_path))))
if not os.path.isfile(request_path):
print(u">>> генерация запроса")
cmd = [openssl_cmd,
'req', '-new',
'-config', os.path.join(output_dir, 'openssl.cnf'), '-batch',
'-key', key_path,
'-out', request_path]
subprocess.run(cmd, env=runtime_env, check=True)
else:
print(u">>> Используем существующий запрос ({})".format(ctime(os.path.getmtime(request_path))))
cmd = [openssl_cmd,
'req',
'-config', os.path.join(output_dir, 'openssl.cnf'),
'-text', '-noout', '-verify',
'-in', request_path]
subprocess.run(cmd, env=runtime_env, check=True)
with open(request_path, 'rt') as request_file:
pyperclip.copy(request_file.read())
print(u">>> Запрос скопирован в буфер обмена")
os.startfile(output_dir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment