Skip to main content
 首页 » 编程设计

python之perl ssh 密码

2025年05月04日10qq号

我正在尝试使用 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 代码,用户名设置正确,但我每次都不得不手动输入密码。

请您参考如下方法:

  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"); 

出于显而易见的原因省略了变量声明...不是问题的确切答案,而是仅使用“Expect 模块”的可行解决方案。