0

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.

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? when the shell is quit, it must destroy the cached info.

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"
run_the_race
  • 1,344
  • 2
  • 36
  • 62

1 Answers1

0

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.

run_the_race
  • 1,344
  • 2
  • 36
  • 62