I\'m writing a shell script to automatically add a new user and update their password. I don\'t know how to get passwd to read from the shell script instead of interactively
Here-document works if your passwd
doesn't support --stdin
and you don't want to (or can't) use chpasswd
for some reason.
Example:
#!/usr/bin/env bash
username="user"
password="pass"
passwd ${username} << EOD
${password}
${password}
EOD
Tested under Arch Linux. This passwd
is an element of shadow-utils
and installed from the core/filesystem
package, which you usually have by default since the package is required by core/base
.
Sometimes it is useful to set a password which nobody knows. This seems to work:
tr -dc A-Za-z0-9 < /dev/urandom | head -c44 | passwd --stdin $user
Nowadays, you can use this command:
echo "user:pass" | chpasswd
The only solution works on Ubuntu 12.04:
echo -e "new_password\nnew_password" | (passwd user)
But the second option only works when I change from:
echo "password:name" | chpasswd
To:
echo "user:password" | chpasswd
See explanations in original post: Changing password via a script
Tested this on a CentOS VMWare image that I keep around for this sort of thing. Note that you probably want to avoid putting passwords as command-line arguments, because anybody on the entire machine can read them out of 'ps -ef'.
That said, this will work:
user="$1"
password="$2"
adduser $user
echo $password | passwd --stdin $user
I stumbled upon the same problem and for some reason the --stdin
option was not available on the version of passwd
I was using (shipped in Ubuntu 14.04).
If any of you happen to experience the same issue, you can work it around as I did, by using the chpasswd
command like this:
echo "<user>:<password>" | chpasswd