Using the passwd command from within a shell script

前端 未结 13 990
遥遥无期
遥遥无期 2020-11-28 04:20

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

13条回答
  •  离开以前
    2020-11-28 04:49

    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
    

提交回复
热议问题