简体   繁体   English

如何在 Django 管理命令(python 脚本)中设置环境变量

[英]How to set an environment variable inside a Django management command (python script)

I am trying to make a Django management command that cache's a user's SUDO password, and the SSH deploy key password, so the second time they run the script it does not ask for them.我正在尝试制作一个 Django 管理命令来缓存用户的 SUDO 密码和 SSH 部署密钥密码,所以他们第二次运行脚本时它不会要求他们。

However the root cause of the problem is that the Environment variables set within the child shell, do not persist to the parent shell when the child shell exits, as explained here: Is it possible to change the Environment of a parent process in Python? However the root cause of the problem is that the Environment variables set within the child shell, do not persist to the parent shell when the child shell exits, as explained here: Is it possible to change the Environment of a parent process in Python?

I don't wish to write this sensitive information to a file.我不希望将此敏感信息写入文件。 So how does one pass info from the management command, back to shell, so next time the command is run it can access the cached credentials?那么如何将管理命令中的信息传递回 shell,以便下次运行该命令时它可以访问缓存的凭据? when the shell is quit, it must destroy the cached info.当 shell 退出时,它必须销毁缓存的信息。

Here's my code if anyone is interested:如果有人感兴趣,这是我的代码:

import os
from subprocess import run, PIPE, Popen
from getpass import getpass

from django.core.management.base import BaseCommand

SUDO_ENV_KEY = 'SUDO_PASSWORD'
GIT_ENV_KEY = 'GIT_PASSWORD'

class Command(BaseCommand):
    def handle(self, **options):
        # ----GET SUDO AUTH----
        if not (sudo_pass := os.environ.get(SUDO_ENV_KEY)):
            sudo_pass = getpass(f"Please enter sudo password: ")
            os.environ[SUDO_ENV_KEY] = sudo_pass
        # Send password via STDIN as bash history is insecure
        command = ['echo', 'Getting sudo...']
        p = Popen(['sudo', '-S'] + command, stdin=PIPE, stderr=PIPE, universal_newlines=True)
        p.communicate(sudo_pass + '\n')[1]

        # ----GET GIT AUTH----
        if os.environ.get(GIT_ENV_KEY) != "True":
            print('Adding GIT SSH deploy key...')
            Cmd.run(['ssh-add', f'/home/username/.ssh/github'], check=True)
            os.environ[GIT_ENV_KEY] = "True"

I worked around the issue by setting the SUDO expire time to be really long, and one can check if the ssh key has been added with ssh-add -l , and if it hasnt been set, just call the command to add it.我通过将 SUDO 过期时间设置为非常长来解决此问题,并且可以检查是否已使用ssh-add -l添加了 ssh 密钥,如果尚未设置,只需调用命令添加它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM