2

I trying to replace password in a simple password file. The new password is garbage and is randomly generated.

For example here is a shadow file with the root account.

root:igXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX+udyyyyyyyyyyyySgY=:10933:0:99999:7::: 

I have the following expression which works 3 out of 4 try.

On the fourth try, I get this error "sed: bad option in substitution expression".

The other time, it works just fine. The password is replaced with a randomly generate string.

sed -i "/root/ s/ *:[^:]*:/:"$(openssl rand -base64 32)":/ " shadow 

Can some one please help explain the problem?

Thanks, Tai

2 Answers 2

2

Your generated password might include characters that are magic to the sed expression. A slightly better approach would be:

$ password=$(openssl rand -base64 32) $ awk -F: -v OFS=: -v p="$password" '$1=="root"{$2=p}1' /etc/shadow 

Since most awk implementations don't have an in-place feature you need to write to a temporary file and replace /etc/shadow (but that's probably safer anyway) or use the handy sponge utility which is part of moreutils.

Sign up to request clarification or add additional context in comments.

3 Comments

@user2019842 Please consider accepting the answer if it helped you resolved your question. You can do so by clicking on the tick mark next to the answer so that it's green. For more information please read this
To be more specific, the base64 encoding can include the '/' and '+' characters, as well as newlines. Since you are using '/' as a separator for the sed commands, the existence of a '/' in the base64 encoded string confuses it...
@twalberg Sssshh, we can't do all the homework! ;-) No seriously, thanks for filling in on my laziness. I was hoping this would be apparent after my vague explanation but I guess it might not be.
1

Use a different control character since / might appear in the password field also.

sed -i "/root/s^A *:[^:]*:^A:"$(openssl rand -base64 32)":^A" shadow 

Here delimiter is ^A (ctrl-A - typed using ctrlVA keys together)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.