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 prompting me for the new password. My code is below.
adduser $1 passwd $1 $2 $2
passwd -l <username> The -l option is used to lock the password of a specified account, and it is available to root only. The result is that the user cannot use the password to log in to the system but can use other means such as SSH public key authentication.
#!/bin/bash echo "Enter Username : " # read username and echo username in terminal read username echo "Enter Password : " # password is read in silent mode i.e. it will # show nothing instead of password. read -s password echo echo "Your password is read in silent mode."
$() – the command substitution. ${} – the parameter substitution/variable expansion.
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
from "man 1 passwd
":
--stdin This option is used to indicate that passwd should read the new password from standard input, which can be a pipe.
So in your case
adduser "$1" echo "$2" | passwd "$1" --stdin
[Update] a few issues were brought up in the comments:
Your passwd
command may not have a --stdin
option: use the chpasswd
utility instead, as suggested by ashawley.
If you use a shell other than bash, "echo" might not be a builtin command, and the shell will call /bin/echo
. This is insecure because the password will show up in the process table and can be seen with tools like ps
.
In this case, you should use another scripting language. Here is an example in Perl:
#!/usr/bin/perl -w open my $pipe, '|chpasswd' or die "can't open pipe: $!"; print {$pipe} "$username:$password"; close $pipe
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With