Change root password from script
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 | MD52a | 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).