linux - 在 shell 脚本中使用 passwd 命令

标签 linux bash unix shell

我正在编写一个 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/

相关文章:

bash - 如果时间大于 X 小于 Y,在黎明之间?

linux - 获取通过管道传输到命令的文件的当前行

bash - 在数字列表中添加前导空格?

linux - Bash - for 循环中的数组

linux - linux 有没有显示文件中指定长度字符串的命令?

c - struct epoll_event memset 还是没有 memset?

linux - 从文件计数出现的次数,grep 停止在一个字符处

linux - 设备树中根节点的模型字段

unix - 我无法弄清楚 ls -alF 在 unix 中给出了什么?

linux - 在后台运行 inotify 脚本