如何使用 perl 脚本进行 ssh,运行命令,并返回输出……?

如何使用 perl 脚本进行 ssh,运行命令,并返回输出……?

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

在网上找到了一些关于此问题的文档,但似乎没有什么信息/清楚的内容。

请帮忙。

答案1

我同意当前的示例看起来很有帮助,但并不总是有效!我以前的示例也包括在内。我根本不是 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;

显然,您需要更改主机名、用户名和 RSA/DSA/等密钥的位置。此外,您还需要兼容库才能在 Ubuntu 上顺利运行:

sudo apt-get install libnet-openssh-compat-perl

最后 — 假设你调用它script.pl— 像这样调用它:

perl -MNet::OpenSSH::Compat=Net::SSH2 script.pl

答案2

您始终可以在 shell 脚本中运行系统调用。只要您可以从 shell 进行 ssh 操作,就无需安装任何东西:

perl -e '$r=`ssh user\@host hostname`; print "Remote host:$r"'

如果您需要自动运行此程序,您有以下几个选择:

  1. 按照说明进行干净利落地完成Oli 的回答
  2. 设置无密码、基于密钥的 ssh 身份验证
  3. 使用sshpass

    首先,从存储库安装它:

    sudo apt-get install sshpass
    

    然后运行这个:

    perl -e '$r=`sshpass -p "password" ssh user\@host hostname`; print "Remote host:$r"'
    

相关内容