3

我正在尝试使用 perl 将 SSH 连接到机器并发出一些命令...

my $ssh = Net::SSH::Perl->new($host);
$ssh->login($user,$pass);
my($stdout, $sterr, $exit) = $ssh->cmd($cmd);
print "$stdout \n"

这是一般的想法,但我仍然被提示输入密码。我也尝试过使用python,也无法通过密码提示。另一方面,Expect 可以很好地处理密码。有谁知道会导致这种情况的原因是什么?

编辑:附加信息

我在一台 linux 机器上使用 putty,然后通过 ssh 连接到更多的 linux 机器上。使用上面的 perl 代码,用户名设置正确,但我最终不得不每次手动输入密码。

4

1 回答 1

0
  use strict;
  use warnings;
  use Expect;

  $exp= Expect->spawn("ssh $host -l $user");

  sleep(1);

  $exp->expect($timeout,"Password:");
  $exp->send("$pass\r");

  $exp->expect($timeout,-re,'>');
  $exp->send("ls -l\r");

  $exp->expect($timeout,-re,'>');
  $exp->send("mkdir aDir\r");

  $exp->expect($timeout,-re,'>');
  $exp->send("chmod 777 aDir\r");

  $exp->expect($timeout,-re,'>');
  $exp->send("exit\r");

出于明显的原因,省略了变量声明......不是问题的确切答案,而是仅使用“期望模块”的可行工作。

于 2015-06-05T22:43:43.340 回答