1
#!/usr/bin/perl

use strict;
use warnings;
my $username = '$ARGV[0]';
my $password = '$ARGV[1]';
use Net::SSH::Expect;
my $ssh = Net::SSH::Expect-> new (
        host => "10.38.228.230",
        password => "lsxid4",
        user => "root",
        raw_pty => 1,
        timeout => 10,
        log_file => "log_file"  
);

my $login_output=$ssh->login();
if ( $login_output =~ /Last/ )
   {
   print "The login for ROOT was successful, Let's see if we can change the password \n";
   $ssh->send("passwd $username");
   $ssh->waitfor ('password:\s*', 10) or die "Where is the first password prompt??";
   $ssh->send("$password");
   $ssh->waitfor ('password:\s*', 10) or die "Where is the Second password promp??";
   $ssh->send("$password");
   $ssh->waitfor('passwd:\s*',5);
   print "The password for $username has been changed successfully \n";
   }
   else
   {
      die "The log in for ROOT was _not_ successful.\n";
   }

我正在尝试通过以 root 身份登录到主机来更改远程主机上的用户密码,但 $username, $password如果我在其工作的代码中提供硬编码值,似乎并没有采用这些值。

在命令行上像这样运行:

bash-3.00# ./test6.pl rak xyz12   
The login for ROOT was successful, Let's see if we can change the password
Where is the first password prompt?? at ./test6.pl line 22.
bash-3.00#

如何远程更改用户密码

4

1 回答 1

1

问题是您在这里使用单引号:

my $username = '$ARGV[0]';
my $password = '$ARGV[1]';

首先,以这种方式引用变量是完全没有必要的。其次,当使用单引号时,内容没有被插值,它只是文字字符串$ARGV[0]

这应该是:

my $username = $ARGV[0];
my $password = $ARGV[1];

但更优雅的解决方案是:

my ($username, $password) = @ARGV;

利用在列表上下文中进行分配的可能性。或者:

my $username = shift;
my $password = shift;

shift根据上下文(无论您是否在子例程中),将隐式地将参数从@ARGVor中移开。@_

于 2013-02-04T12:09:55.337 回答