Aeris Aeris - 4 months ago 28
Bash Question

Replace sha512 hash with sed via variable

I'm using a code to create a sha512 hashed password.

source ~/xyz.cfg

test=$(python -c "from passlib.hash import sha512_crypt; print sha512_crypt.encrypt('${XYZ_PASS}')")

sed 's/^"password.*$/"password" : "sha512|'$test'",/' /etc/xyz.json


${XYZ_PASS} is a password from another file and its stored hashed in test

But now the Problem:

The sha512 hash should replace another one:

Original line:

"password": "sha512|some-hash",

Line i want to sed into the file:

"password": "sha512|newshash",

newhash is the hash stored in test

The sed command doesn't work at all, I really have problems using it, im trying to get the solution for hours now.

best regards

Edit:

After this command

test=$(python -c "from passlib.hash import sha512_crypt; print sha512_crypt.encrypt('${XYZ_PASS}')")


Test should (and does) contain a hash like this:

$6$rounds=60000$ca.5CQtZct/vKXxo$nu.wS1OSYo6dz02zvo9QJTkzz2TEg9stQF3OsOvauGCTu36P6463P3Cmpron6dwK.Dz7.RT2Az56f9NbEcw.g1


Edit:
https://github.com/Eugeny/ajenti/blob/master/config.json is the json

I'm trying to replace the password hash with my own

Answer

There are two issues: (1) in the real json file, "password" is not at the beginning of the line, and (2) test contains / which is a sed-active character which needs to be escaped:

$ test='$6$rounds=60000$ca.5CQtZct/vKXxo$nu.wS1OSYo6dz02zvo9QJTkzz2TEg9stQF3OsOvauGCTu36‌​P6463P3Cmpron6dwK.Dz7.RT2Az56f9NbEcw.g1'
$ sed 's/^[[:space:]]*"password.*$/"password" : "sha512|'"${test//\//\\/}"'",/' xyz.json
"password" : "sha512|$6$rounds=60000$ca.5CQtZct/vKXxo$nu.wS1OSYo6dz02zvo9QJTkzz2TEg9stQF3OsOvauGCTu36‌​P6463P3Cmpron6dwK.Dz7.RT2Az56f9NbEcw.g1",

Alternatively, consider using awk which avoids the escaping issues with test:

$ awk -v hash="$test" '$1~/^"password/{$0="   \"password\" : \"sha512|" hash "\","} 1' xyz.json
   "password" : "sha512|$6$rounds=60000$ca.5CQtZct/vKXxo$nu.wS1OSYo6dz02zvo9QJTkzz2TEg9stQF3OsOvauGCTu36‌​P6463P3Cmpron6dwK.Dz7.RT2Az56f9NbEcw.g1",

To save in-place

Using sed:

sed -i.bak 's/^[[:space:]]*"password.*$/"password" : "sha512|'"${test//\//\\/}"'",/' xyz.json

Using GNU awk:

awk -i inplace -v hash="$test" '$1~/^"password/{$0="   \"password\" : \"sha512|" hash "\","} 1' xyz.json

Using BSD awk:

awk -v hash="$test" '$1~/^"password/{$0="   \"password\" : \"sha512|" hash "\","} 1' xyz.json >tmp.json && mv tmp.json xyz.json