Jared Jared - 1 year ago 106
Linux Question

using the passwd command from within a shell script

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

Answer Source

from "man 1 passwd":

          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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download