在 shell 脚本中使用 passwd 命令 [英] Using the passwd command from within a shell script

查看:67
本文介绍了在 shell 脚本中使用 passwd 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 shell 脚本来自动添加一个新用户并更新他们的密码.我不知道如何让 passwd 从 shell 脚本中读取,而不是以交互方式提示我输入新密码.我的代码如下.

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

推荐答案

来自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

[更新]评论中提出了一些问题:

[Update] a few issues were brought up in the comments:

您的 passwd 命令可能没有 --stdin 选项:使用 chpasswd实用程序,如 ashawley.

Your passwd command may not have a --stdin option: use the chpasswd utility instead, as suggested by ashawley.

如果您使用 bash 以外的 shell,echo"可能不是内置命令,并且 shell 将调用 /bin/echo.这是不安全的,因为密码将显示在进程表中,可以使用 ps 之类的工具查看.

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.

在这种情况下,您应该使用另一种脚本语言.这是 Perl 中的示例:

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

这篇关于在 shell 脚本中使用 passwd 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆