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?
I’m looking for a way to change a root user’s password on a Linux
Share
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:So a shadow password string might look like this:
$5$saltysalt$KhboodWTnuXJ5siXvWx5mxYXbnuNJOxROfD1inCILfDIn 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:
Compile with
cc mkpass.c -o mkpass -lcryptand then run with the plaintext password and salt string to generate a string you can put into/etc/shadow: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).