[英]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.