Here's an example which uses the
pwgen program to make a nice password and then uses the
makepasswd program to generate the hash. The password of the user is then set using the
usermod program.
It is important that a cleartext password is never sent to a program as a command line parameter to prevent it being snooped by another user who runs
ps at just the right time.
Code:
#!/bin/bash
# Make sure new file which contains password is private
touch pass.txt
chmod 600 pass.txt
# generate a nice secure password and put it in a file
pwgen > pass.txt
# get the password hash
ph=$(makepasswd --clearfrom=pass.txt --crypt-md5 |awk '{print $2}')
# Set the password
usermod -p $ph bob
Note that
makepasswd and
pwgen are not installed by default in most distros. In Debian/Ubuntu, there are packages with the same names as the programs for them.
Storing the cleartext password in a file like this is also a risky business. Only root can read the file, and anyone sitting in front of a root shell can reset anyone's password anyway, so it's not that big a deal in itself. However, you should be very careful about this file.
Not only do you need to prevent the file getting made publicly readable, but you need to protect the media on which it has been stored. Be aware that even if you have deleted the file, the contents will remain on the disk for some time, and may thus be recovered with the right tools... Writing a cleartext password to a file may contravene your employer's security policy, or other security regulations, and it is generally a Bad Idea.
There are some cases when it is (IMO) acceptable. For example making large numbers of new accounts for a student class, where the password will be printed on some private letter. In such cases you should also set the flag on the account which forces the user to change their password when they first log in so that anyone who has snooped the cleartext password will not be able to use it without you knowing (as they will have to reset the password, and presumably the student would complain when the written password does not work).
Having said all that, there are probably better approaches for that sort of thing too.
May I ask what the situation is which prompted the question?