【问题标题】:ssh perl script not runningssh perl 脚本未运行
【发布时间】:2016-08-16 20:01:00
【问题描述】:

我正在尝试编写一个脚本,它将通过 perl 连接到远程机器。

我不确定出了什么问题,但是当我运行脚本时,它会提示我输入 root 密码,并在我输入密码后以空白输出结束。

这是我的脚本:

#!/usr/bin/perl
use strict;
use warnings;

my @id=`ssh expert\@x.x.x.x`;
print"@id";

【问题讨论】:

  • 在 shell 提示符下输入“ssh Expert@x.x.x.x”会发生什么?
  • 你没有给ssh一个目标命令,你会得到一个shell提示符。所以,你想要的是my @id = `ssh expert@... date`;(例如)
  • 我可以在 shell 提示符中使用 ssh 来远程登录

标签: bash perl shell ssh


【解决方案1】:

这就是您要求程序执行的操作。这一行

`ssh expert\@x.x.x.x`
  • 使用给定参数启动一个运行 ssh 的新子进程
  • 退出该子进程并从 ssh 返回任何文本输出

您可能需要在连接后与远程系统进行交互,因此您要么需要 perl 进程来连接到远程系统,要么需要能够与散列在退出之前连接的子进程

第一个是迄今为止最简单的解决方案。如果您使用Net::OpenSSH 模块并阅读其文档,您将看到可以通过创建对象来打开连接。然后,您可以使用该对象的 capture 方法发送命令并检索输出

【讨论】:

  • 思考:为什么要而不是听?啊英语我们爱你
【解决方案2】:

我建议不要在 perl 代码中使用系统 ssh 命令,原因如下:

  1. 它使解析输出变得困难
  2. 错误处理变得困难
  3. 编程灵活性较低

而是使用 CPAN 库,例如Net::SSH::Perl 用于从 Perl 代码触发 SSH 命令。

使用这个模块打开一个shell很简单,如下所述:

$ssh->shell

Opens up an interactive shell on the remote machine and connects it to your STDIN. This is most effective when used with a pseudo tty; otherwise you won't get a command line prompt, and it won't look much like a shell. For this reason--unless you've specifically declined one--a pty will be requested from the remote machine, even if you haven't set the use_pty argument to new (described above).

This is really only useful in an interactive program.

In addition, you'll probably want to set your terminal to raw input before calling this method. This lets Net::SSH::Perl process each character and send it off to the remote machine, as you type it.

To do so, use Term::ReadKey in your program:

    use Term::ReadKey;
    ReadMode('raw');
    $ssh->shell;
    ReadMode('restore');

下面是一个简单的示例,它演示了使用同一个模块来触发和解析命令输出是多么容易:

  use Net::SSH::Perl;
    my $ssh = Net::SSH::Perl->new($host);
    $ssh->login($user, $pass);
    my($stdout, $stderr, $exit) = $ssh->cmd($cmd);

指向 Net::SSH::Perl cpan 文档的链接:http://search.cpan.org/~schwigon/Net-SSH-Perl-1.42/lib/Net/SSH/Perl.pm

我更喜欢使用的另一个模块是 Net::OpenSSH: http://search.cpan.org/~salva/Net-OpenSSH-0.70/lib/Net/OpenSSH.pm

use Net::OpenSSH;

  my $ssh = Net::OpenSSH->new($host);
  $ssh->error and
    die "Couldn't establish SSH connection: ". $ssh->error;

  $ssh->system("ls /tmp") or
    die "remote command failed: " . $ssh->error;

  my @ls = $ssh->capture("ls");
  $ssh->error and
    die "remote ls command failed: " . $ssh->error;

  my ($out, $err) = $ssh->capture2("find /root");
  $ssh->error and
    die "remote find command failed: " . $ssh->error;

  my ($rin, $pid) = $ssh->pipe_in("cat >/tmp/foo") or
    die "pipe_in method failed: " . $ssh->error;

  print $rin "hello\n";
  close $rin;

【讨论】:

    猜你喜欢
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 2010-09-26
    • 2012-09-18
    • 1970-01-01
    • 2014-12-29
    相关资源
    最近更新 更多