0

I am working on a bash script to update passwords in a config file.

  • The configuration file, settings.py, is a python file
  • The password in the file is a variable, that looks like this:

TEST_PASSWORD = 'SomeValue'

What I need to do is enter in a command into the Linux terminal to scan into that file, and replace 'SomeValue' with what I enter.

I imagine some pseudocode would look like:

update_password(){
    echo "What do you want to update the password to?"
    new_pass = -> Read in user value into

    -> update settings.py and change:
    TEST_PASSWORD = 'SomeValue'
    to
    TEST_PASSWORD = "'" + new_pass + "'"
}

(it must be enclosed as a string in the settings.py file)

So far, I have tried a one-liner:

sed -i 's/TEST_PASSWORD = 'test'/TEST_PASSWORD = 'new_val'/g' test/settings.py

and nothing happens. As in, the file doesn't change at all. (referenced from here)

The complete program looks like:

#!/bin/bash

read -p "Enter a password: " password

echo "Got password"
echo " "

sed -i 's/TEST_PASSWORD = / TEST_PASSWORD = $password/g' test/settings.py

But in settings.py, it changes:

TEST_PASSWORD = 'test' to TEST_PASSWORD = $password'test'

How can I change the value of the TEST_PASSWORD in settings.py to the value that the user enters, without knowing what the current password is?

For Reference: awk -F= '/^NAME/{print $2}' /etc/os-release yields: "Red Hat Enterprise Linux Server"

artemis
  • 6,857
  • 11
  • 46
  • 99
  • `sed -i "s/TEST_PASSWORD = .*/TEST_PASSWORD = '$password'/g" test/settings.py` – Wiktor Stribiżew Jan 09 '20 at 00:28
  • You can't use single quotes inside single-quoted strings. – Barmar Jan 09 '20 at 00:42
  • Should I ask @WiktorStribiżew to post this as an answer, or delete the question? I think this should be an answer. It worked. – artemis Jan 09 '20 at 00:46
  • 1
    IMHO, a duplicate of [How do I use sed to change my configuration files, with flexible keys and values?](https://stackoverflow.com/questions/5955548/how-do-i-use-sed-to-change-my-configuration-files-with-flexible-keys-and-values) – Wiktor Stribiżew Jan 09 '20 at 00:48
  • But also, don't store passwords in your Python scripts in the first place. Make them read a configuration file or environment variable instead of hard-coding a password, especially, one which then needs to be replaced using this very brittle approach. – tripleee Jan 09 '20 at 05:05

0 Answers0