繁体   English   中英

通过ssh运行远程bash命令

[英]Run a remote bash command through ssh

我有以下脚本,我计划用于在远程服务器上执行bash命令。 每次运行此脚本时,都应检查远程MySQL(PXC)服务器是否正在进行SST。

#!/usr/bin/perl

use strict;
use warnings;

my $time = localtime();

my $file = '/db-common-list/names.txt';
open my $info, $file or die "Could not open $file: $!";

while ( my $hostname = <$info> )  {

    my $wsrep_check = `ssh $hostname ps -ef |grep mysql | grep wsrep_sst_xtrabackup-v2`;

    if ( index($wsrep_check, 'State transfer in progress, setting sleep higher mysqld') != -1 ) {
        print "$time: Server $hostname";
        last if $. == 2;
    }
}

close $info;

/db-common-list/names.txt里面是脚本应该逐行循环的数据库列表。 所以它看起来像这样:

db-test-1
db-test-2
db-test-3
db-test-4
...

但是当我运行脚本时,命令行只是挂起并且从不显示任何内容,此时我必须手动强制脚本停止执行。 所以几分钟之后只有脚本挂在终端上,我使用Ctrl-D来停止脚本,我得到了这个:

thegeorgia@cron-db$ ./test.cron
Connection to db-test-1 closed.
Connection to db-test-2 closed.
thegeorgia@cron-db$ ./test.cron

我可以ssh和ping这些远程服务器,如下面的服务器所示,这不是问题肯定:

thegeorgis@cron-db$ ping db-test-1
PING db-test-1 (10.1.4.205) 56(84) bytes of data.
64 bytes from db-test-1 (10.1.4.205): icmp_seq=1 ttl=64 time=0.263 ms
64 bytes from db-test-1 (10.1.4.205): icmp_seq=2 ttl=64 time=0.222 ms 

涉及的所有服务器都在运行Ubuntu。

注意:正如Borodin所建议的那样,我将chomp添加如下:

    while( my $hostname = <$info>)  {
    my $server = chomp( $hostname );
    my $wsrep_check = `ssh $server ls`;
         if ( index($wsrep_check, 'State transfer in progress, setting sleep higher mysqld') != -1 ){
            print "$time: Server $server";
       }
last if $. == 2;
}

当我运行perl脚本时,我现在得到以下错误:

ssh: connect to host 1 port 22: Invalid argument
ssh: connect to host 1 port 22: Invalid argument

解:

#!/usr/bin/perl -w

use strict;
use warnings;

my $time = localtime();
my $file = '/db-common-list/names.txt';
open my $info, $file or die "Could not open $file: $!";

while( my $hostname = <$info>)  {
    chomp( $hostname );
    my $wsrep_check = `ssh $hostname ps -ef |grep mysql | grep wsrep_sst_xtrabackup-v2`;
         if ( $wsrep_check ne "" ){
            print "$time: Server $hostname\n";
       }
}
close $info;

你需要

chomp $hostname;

在您的ssh命令之前从读取中删除尾随换行符

我也怀疑你的last if $. == 2 last if $. == 2应该在if之外

Perl内置了对正则表达式的支持,因此很少需要调用index

if ( index($wsrep_check, 'State transfer in progress, setting sleep higher mysqld') != -1 ) { ... }

通常是写的

if ( $wsrep_check =~ /State transfer in progress, setting sleep higher mysqld/ ) { ... }

但是你写的很好

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM