Skip to content

Instantly share code, notes, and snippets.

@donspaulding
Created September 11, 2014 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donspaulding/9e831d1fb3bee213e17f to your computer and use it in GitHub Desktop.
Save donspaulding/9e831d1fb3bee213e17f to your computer and use it in GitHub Desktop.
Generating a CSR from python using sh
def generate_csr(domain):
import tempfile
import shutil
from sh import openssl
csr_data = "/C=%s/ST=%s/L=%s/O=%s/CN=www.%s" % (
domain.country.upper(),
domain.full_state,
domain.city,
domain.letterhead_name,
domain.name,
)
temp_dir = tempfile.mkdtemp(dir=settings.DATA_DIR)
csr_file = os.path.join(temp_dir, domain.name + '.csr')
key_file = os.path.join(temp_dir, domain.name + '.key')
open(key_file, 'w').write(domain.ssl_cert_key)
openssl.req(
'-new',
'-key', key_file,
'-out', csr_file,
'-subj', csr_data,
)
domain.ssl_csr = open(csr_file).read()
shutil.rmtree(temp_dir)
if os.path.exists(key_file):
raise Exception("The private key %s was not deleted!" % key_file)
@ronak2303
Copy link

how do i use this code, what library i need to import. we just need to pass domain name to it.

@donspaulding
Copy link
Author

@ronak2303 This gist requires both the sh library, as well as a local installation of the openssl CLI.

If you have further questions, please email me at donspauldingii@gmail.com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment