Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux set root password on etc/shadow file

I'm building a ram filesystem, and I generated a "/" directory. I would like to set a default root password on the generated "etc/shadow" file. The actual file is:

root:*:15980:0:99999:7:::
bin:*:15980:0:99999:7:::
daemon:*:15980:0:99999:7:::
adm:*:15980:0:99999:7:::
...
.....

I would like to replace "root:*:" with "root:Hashedpassword:", I know it is very easy to replace "*" with the "HASHEDPASSWORD", But it should by done using the pattern "root:anything:", and this also should not be difficult, even-though I would like to ask about it here coz it may be useful for others.

For example:

the password I want to set is "centos"

The salt is "xyz"

I get the hashed pass:

pass=$(openssl passwd -1 -salt xyz centos)

Then I would like te replace "anything" in "root:anything:" with "root:Hashedpassword:" with "sed" command.

like image 479
Yahya Yahyaoui Avatar asked Sep 01 '25 10:09

Yahya Yahyaoui


1 Answers

You could do it with GNU sed like

sed -i -e "s/^root:[^:]\+:/root:$pass:/" etc/shadow

if $pass might have / characters in it you can use a different separator, like , if that won't be there. You can do that like:

sed -i -e  "s,^root:[^:]\+:,root:$pass:," etc/shadow

if you do not have GNU sed you may not have -i or it may require an argument.

You could also use awk to do this:

awk -F: "BEGIN {OFS=FS;} \$1 == \"root\" {\$2=\"$pass\"} 1" etc/shadow

if you have a recent version of GNU awk you can do it with the -i like so:

awk -i inplace -F: "BEGIN {OFS=FS;} \$1 == \"root\" {\$2=\"$pass\"} 1" etc/shadow
like image 130
Eric Renouf Avatar answered Sep 03 '25 01:09

Eric Renouf