Change root password from script
bash, linux, passwords, shell
Solution
The password hash is in `/etc/shadow`. You can simply replace it with a generated (salted) hash. The format for the password hash is described in crypt(3). The default is DES, but on glibc2 systems it can contain one of several different encryption methods:
ID Method
1 MD5
2a Blowfish (not in mainline glibc; added in some Linux distributions)
5 SHA-256 (since glibc 2.7)
6 SHA-512 (since glibc 2.7)
So a shadow password string might look like this: `$5$saltysalt$KhboodWTnuXJ5siXvWx5mxYXbnuNJOxROfD1inCILfD`
In this case the first $5$ part indicates it's a SHA-256 hash, the middle part is the salt and the rest is the actual hash.
To generate one, best use the system's crypt(3) function, for example with a minimal C program:
#include <stdio.h>
#include <crypt.h>
int main(int argc, char *argv[]) {
printf("%s\n", crypt(argv[1], argv[2]));
}
Compile with `cc mkpass.c -o mkpass -lcrypt` and then run with the plaintext password and salt string to generate a string you can put into `/etc/shadow`:
./mkpass yourpassword yoursalt # DES (default)
./mkpass yourpassword '$6$yoursalt$encrypted' # SHA-512 (quote your $)
The second form may not be supported on older Linux systems. Best look at the existing string in your shadow file and use the same hash type (from the $id$ list at the top).
Problem
I'm looking for a way to change a root user's password on a Linux system through a bash script, without booting the system. The only things I have found so far are to either remove the password, or to use a chroot, which I prefer not to use. I know how to empty the root password, but I need to change it to a different password defined earlier in the script. I have root access to the entire file system. The system is using shadow passwords, is there a way to generate an encrypted shadow password without logging in/chrooting? Any other ways to change the root password from script?