天天看點

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

繼續閱讀