2

I apologize if this question is too basic, but I'm really very very new to perl. Now I want to write the following two lines of code in one line:

perl -e 'print crypt("my_password","\$6\$my_salt\$")'

perl -pe 's|(root):(\$.*?:)|\1:my_encrypted_password:|' /etc/shadow

Basically I want to replace the my_encrypted_password with what's being printed from the first line. But I have no idea how to write it correctly? Any help will be greatly appreciated.

  • 2
    I'm not sure if modifying /etc/shadows with perl is really a good idea... – michas Jul 18 '15 at 11:41
  • I'm trying to mount the virtual machine's disk to the host and reset the virtual machine's root password. – Elgs Qian Chen Jul 18 '15 at 11:47
  • 1
    Maybe passwd -R might be a better solution. – michas Jul 18 '15 at 11:56
  • @michas can you make it a bit more clear how to use passwd -R? Thanks. – Elgs Qian Chen Jul 18 '15 at 12:43
  • Have a look at man passwd. Just add the mount point of your VM disk and passwd should use the shadow file there. – michas Jul 20 '15 at 5:36
2

You probably mean something like this:

perl -pe 's|(?<=root:)[^:]*|crypt("my_password","\$6\$my_salt\$")|e' /etc/shadow

From perldoc perlre:

    Substitution-specific modifiers described in

    "s/PATTERN/REPLACEMENT/msixpodualngcer" in perlop are:

      e  - evaluate the right-hand side as an expression

On the right side you can use $& to refer to the matching part and $1 for the first captured part and so on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.