如何使用 perl scipt ssh,运行命令,并返回输出...?

kir*_*bnl 0 ssh command-line perl

正如问题中明确解释的那样,请给我一个使用 perl 脚本 ssh 到机器的选项,在那里运行几行脚本,然后将输出返回到源机器。

在网上找到了一些关于此的文档,但似乎没有任何信息/清晰。

请帮忙。

Oli*_*Oli 5

我同意当前的示例看起来很有帮助,但并不总是有效!我以前的例子包括在里面。我根本不是 Perl 专家,但我拼凑了以下内容,它对我有用:

#!/usr/bin/perl -w
use strict;

use Net::SSH2;

my $ssh2 = Net::SSH2->new();
$ssh2->connect('tank') or die $!;
my $auth = $ssh2->auth_publickey(
    'oli',
    '/home/oli/.ssh/id_rsa'
);

my $chan2 = $ssh2->channel();
$chan2->blocking(1);

# This is where we send the command and read the response
$chan2->exec("uname -a\n");
print "$_" while <$chan2>;

$chan2->close;
Run Code Online (Sandbox Code Playgroud)

显然,您需要更改 RSA/DSA/etc 密钥的主机名、用户名和位置。此外,您需要使用 compat 库才能在 Ubuntu 上正常运行:

sudo apt-get install libnet-openssh-compat-perl
Run Code Online (Sandbox Code Playgroud)

最后——假设你这样称呼它script.pl——这样称呼它:

perl -MNet::OpenSSH::Compat=Net::SSH2 script.pl
Run Code Online (Sandbox Code Playgroud)