我正在编写一个 shell 脚本来自动添加一个新用户并更新他们的密码。我不知道如何让 passwd 从 shell 脚本中读取,而不是交互式地提示我输入新密码。我的代码如下。
adduser $1 passwd $1 $2 $2
最佳答案
来自“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.
所以你的情况
adduser "$1"
echo "$2" | passwd "$1" --stdin
[更新]评论中提出了一些问题:
您的 passwd
命令可能没有 --stdin
选项:使用 chpasswd
根据 ashawley 的建议,使用实用程序.
如果您使用 bash 以外的 shell,“echo”可能不是内置命令,
shell 会调用 /bin/echo
。这是不安全的,因为密码
将显示在进程表中,并且可以使用 ps
等工具查看。
在这种情况下,您应该使用另一种脚本语言。这是 Perl 中的一个示例:
#!/usr/bin/perl -w
open my $pipe, '|chpasswd' or die "can't open pipe: $!";
print {$pipe} "$username:$password";
close $pipe
关于linux - 在 shell 脚本中使用 passwd 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/714915/