Linux – Change the root password of a Linux image

compilinglinuxpassword

I'm building a jessie build of Debian. Passwords are saved in /etc/shadow in the build tree, but they are salted obviously so I cannot change it just by editing the file. If this was my installed system, I could call passwd, but here I want to change the password in the file in the build tree.

How do I change the root password before I flash a SD with a new build?

Best Answer

At the stage where you have a directory tree containing a file …/etc/shadow (before building the filesystem image), modify that file to inject the password hash(es) that you want to have.

The easiest way to do that is with recent enough versions of the chpasswd tool from the Linux shadow utilities suite (Debian wheezy is recent enough) with the -R option. Sample usage:

chpasswd -R /path/to/build/tree <passwords.txt

with passwords.txt containing lines like

root:swordfish
alibaba:opensesame

If your build environment doesn't support chpasswd -R, you can use a tool that generates a password hash by calling the crypt function and inject that into the shadow file by text manipulation. For example (untested code):

#!/usr/bin/python
import base64, crypt, os, re, sys
for line in sys.stdin.readlines():
    (username, password) = line.strip().split(":")
    salt = "$6$" + base64.b64encode(os.urandom(6))
    hashes[username] = crypt.crypt(password, salt)
old_shadow = open("etc/shadow")
new_shadow = open("etc/shadow.making", "w")
for line in old_shadow.readlines():
    (username, password, trail) = line.lstrip().split(":", 3)
    if hashes.has_key(username):
        line = username + ":" + hashes[username] + ":" + trail
    new_shadow.write(line)
old_shadow.close()
new_shadow.close()
os.rename("etc/shadow.making", "etc/shadow")
Related Question