perl遠程執行多臺服務器shell命令

  在生成環境中一般運維須要執行很是多的重複命令,一臺可能還好 多臺就杯具了。尤爲有時候要批量去更新多臺服務器的文件,或者是刪除。
   一個好運維都是懶惰的,因此本身寫了個perl腳本能夠遠程去執行shell命令,很靈活。2個配置文件,一個管理服務器信息,一個放所須要執行的命令。
code:
#!/usr/bin/perl
use strict;
use Net::SSH::Expect;
my @ssh_list;
my $ssh_txt='ip_list.txt';
my $command_txt='command_txt.txt';
open FH,$ssh_txt;
        while(<FH>){
        @ssh_list=split;
        print "正在登錄".$ssh_list[0]."...\n";
        &ssh_conn("$ssh_list[0]","$ssh_list[1]","$ssh_list[2]","$ssh_list[3]");
        }
        close    FH;

sub    ssh_conn(){
                my($host,$port,$user,$pass) = @_;
                my $ssh = Net::SSH::Expect->new(
                                host        =>            $host,
                                port        =>            $port,
                                user        =>            $user,
                                password                =>$pass,
                                no_terminal         =>0,
                                raw_pty =>1,
                                timeout =>            3,
                                );
                                                $ssh->debug(0);
                                                $ssh->run_ssh() or die "SSH process coundn't start:$!";
                                                $ssh->waitfor( '\(yes\/no\)\?$', 1 ); #交互式修改密碼,給予2秒的時間
                                                $ssh->send("yes\n");
                                                $ssh->waitfor( 'password:\s*$/', 1);
                                                $ssh->send("$ssh_list[3]");
                                                $ssh->send("su - root");
                                                $ssh->waitfor( 'password:\s*$/', 1);
                                                $ssh->send("$ssh_list[4]");
                                                #$ssh->waitfor("#\s*",2);
                                                open F1,$command_txt;
                                                while(<F1>){


                                                my @command=split/\n/,$_;
                                                print "$command[0]-->    ";
                                                $ssh->exec("$command[0]");

                                                print "$ssh_list[0]命令執行完畢\n";


                                                }
                                                close F1;
                                                $ssh->close();
下面是2個文件內容。
[root@nagios script]# cat ip_list.txt
192.168.2.101    22    mcshell     psswd    server1
192.168.2.102    22    mcshell     psswd    server2
192.168.2.103    22    mcshell     psswd    server3
[root@nagios script]# cat command_txt.txt
touch /home/mcshell/file1
touch /home/mcshell/file2
 
執行結果:
固然我這裏爲了測試方便,用了寫的比較簡單,你們也能夠發揮想象,直接把複雜的shell或者perl密令直接放在command_txt.txt中。一樣能夠批量處理
相關文章
相關標籤/搜索