天天看点

Perl Net::openSSH 远程登录多台机器执行脚本

需求:在多台机器需要同时执行文件,并且是不定期的,crontab不适用了,没办法了写了这个Script,简单也没什么错误提示,只为执行即可;

前提:在跳板机上已经和机器的ssh打通;在Script机器上安装perl模块Net::openSSH

Net-OpenSSH-0.57.tar.gz

解压,发现需要安装其他模块;

<a target="_blank" href="http://blog.51cto.com/attachment/201303/162630400.jpg"></a>

逐个安装:

<a target="_blank" href="http://blog.51cto.com/attachment/201303/163129552.jpg"></a>

将上面的四个模块安装完毕;

编写脚本:allget.pl

#!/usr/bin/perl

use strict;

use Net::OpenSSH;

open (HD,"/home/user/alljd") || die "Cannot find file:$!\n";

my @jd=&lt;HD&gt;;

close (HD);

my $jd;

foreach $jd(@jd) {

chomp ($jd);

my $user="user";

my $host=$jd;

#my $passphrase='user密码';

my $key='/home/user/.ssh/id_rsa';

my $cmd="ls";

my %param = (

    user =&gt; $user,

#    passphrase =&gt; $passphrase,

    key_path =&gt; $key,

    timeout =&gt; 60

    );

my $ssh = Net::OpenSSH-&gt;new($host,%param);

my ($stdout,$stderr) = $ssh-&gt;capture2("sudo ./get.pl");

if ($stdout){

    print $host is $stdout;

} else {

    print $ssh-&gt;error;

    $stderr and print $stderr;

}

alljd是个文本文件,get.pl是远程机器上的Script;

测试正常;

本文转自 西索oO 51CTO博客,原文链接:http://blog.51cto.com/lansgg/1153376

继续阅读