我有一个 bash 脚本,它会要求您输入密码,然后需要使用 pam 验证密码,我已经安装了它,libpam0g-dev
因为我知道我需要它,但我究竟如何使用 pam 验证密码?pam 如何让我知道密码是否有效?
答案1
不是 bash,但你可以在 bash 脚本中使用 Perl 脚本:P
首次安装libauthen-pam-perl
sudo apt-get install libauthen-pam-perl
之后创建一个新的 Perl 脚本,例如,名称为foo
...
#!/usr/bin/env perl
use Authen::PAM;
use POSIX qw(ttyname);
$service = "login";
$username = $ARGV[0];
$password = $ARGV[1];
$tty_name = ttyname(fileno(STDIN));
sub my_conv_func {
my @res;
while ( @_ ) {
my $code = shift;
my $msg = shift;
my $ans = "";
$ans = $username if ($code == PAM_PROMPT_ECHO_ON() );
$ans = $password if ($code == PAM_PROMPT_ECHO_OFF() );
push @res, (PAM_SUCCESS(),$ans);
}
push @res, PAM_SUCCESS();
return @res;
}
ref($pamh = new Authen::PAM($service, $username, \&my_conv_func)) ||
die "Error code $pamh during PAM init!";
$res = $pamh->pam_set_item(PAM_TTY(), $tty_name);
$res = $pamh->pam_authenticate;
if ($res == PAM_SUCCESS()) {
printf ("%s\n","Success");
}
else {
printf ("%s\n","Failure");
}
基于这个答案经过一些修改
从man foo
;)
NAME
foo - password test
SYNOPSIS
foo username password
DESCRIPTION
coming soon
OPTIONS
no options
例子:
$ sudo ./foo foo wWeErRt # wrong password
Failure
$ sudo ./foo foo wWeErRtT # correct password
Success
在你的脚本中:
some code
ret=$(foo "$username" "$password")
some code