将 subprocess.run 用于 GRPC ssl 脚本 [Python] 时遇到问题

Trouble using subprocess.run for GRPC ssl scripting [Python]

我在编写为 GRPC 服务生成 SSL 密钥和证书的 python 脚本时遇到困难。我正在尝试编写一个函数,通过将 ip 传递给它,可以 运行 此 file 中的命令。这是我写的,但是我收到一个我不明白的错误,我会在底部列出

我的函数:

def cert_create(ip):
    subprocess.run(['SERVER_CN=', ip])
    subprocess.run(['openssl', 'genrsa', '-passout', 'pass:1111', '-des3', '-out', 'ca.key', '4096'])
    subprocess.run(['openssl', 'req', '-passin', 'pass:1111', '-new', '-x509', '-days', '3650', '-key', 'ca.key', '-out', 'ca.crt', '-subj', '"/CN=${SERVER_CN}"'])
    subprocess.run(['openssl', 'genrsa', '-passout', 'pass:1111', '-des3', '-out', 'server.key', '4096'])
    subprocess.run(['openssl', 'req', '-passin', 'pass:1111', '-new', '-key', 'server.key', '-out', 'server.csr', '-subj', '"/CN=${SERVER_CN}"', '-config', 'ssl.cnf'])
    subprocess.run(['openssl', 'x509', '-req', '-passin', 'pass:1111', '-days', '3650', '-in', 'server.csr', '-CA', 'ca.crt', '-CAkey', 'ca.key', '-set_serial', '01', '-out', 'server.crt', '-extensions', 'req_ext', '-extfile', 'ssl.cnf'])
    subprocess.run(['openssl', 'pkcs8', '-topk8', '-nocrypt', '-passin', 'pass:1111', '-in', 'server.key', '-out', 'server.pem'])

错误:

Traceback (most recent call last):
  File "/home/nocnoc/Documents/deployment/ansible/cert_script.py", line 24, in <module>
    cert_create("HEYA")
  File "/home/nocnoc/Documents/deployment/ansible/cert_script.py", line 11, in cert_create
    subprocess.run(['SERVER_CN=', ip])
  File "/usr/lib/python3.8/subprocess.py", line 489, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/usr/lib/python3.8/subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/lib/python3.8/subprocess.py", line 1702, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'SERVER_CN='

有什么想法吗?

您试图在不调用 shell 的情况下设置 shell 变量。

执行此操作的正确方法是在 Python 脚本中设置变量。

import os

os.environ['SERVER_CN'] = ip

这样,其余大部分代码都可以正常工作,但您还需要更改

    subprocess.run(   # wrapped for legibility
        ['openssl', 'req', '-passin', 'pass:1111',
         '-new', '-key', 'server.key', '-out', 'server.csr',
         '-subj', '"/CN=${SERVER_CN}"', '-config', 'ssl.cnf'])

进入

    subprocess.run(
        ['openssl', 'req', '-passin', 'pass:1111',
         '-new', '-key', 'server.key', '-out', 'server.csr',
         '-subj', '/CN=' + ip, '-config', 'ssl.cnf'])

另请注意固定引用;在原始 shell 脚本中,-subj 参数周围的双引号将被 shell 去除,如果将它们放在没有 [=31= 的地方,将会产生错误] 在那里并剥离它们。

(更直接地说,如果 subprocess.run(['SERVER_CN=', ip]) 有效,它将 运行 SERVER_CN= ip 与 space,这将在 shell,或者如果您的 PATH 中有一个名为 SERVER_CN= 的命令,则 运行 将 IP 地址作为其第一个参数。)