Perl脚本,用于检查是否可以通过ssh连接到远程服务器
我有一个perl脚本,在实际执行ssh之前,我想首先检查是否可以ssh到服务器中。因此,如果可以使用ssh,那么继续使用ssh将其连接到该服务器,否则将适当地处理此异常 因此,我有一个脚本,它通过一个包含数据库列表的文本文件,尝试通过ssh连接到每个服务器以执行bash命令,该命令检查服务器是否正在执行MySQL SST:Perl脚本,用于检查是否可以通过ssh连接到远程服务器,perl,ssh,Perl,Ssh,我有一个perl脚本,在实际执行ssh之前,我想首先检查是否可以ssh到服务器中。因此,如果可以使用ssh,那么继续使用ssh将其连接到该服务器,否则将适当地处理此异常 因此,我有一个脚本,它通过一个包含数据库列表的文本文件,尝试通过ssh连接到每个服务器以执行bash命令,该命令检查服务器是否正在执行MySQL SST: #!/usr/bin/perl -w use strict; use warnings; use 5.010; use DBI; use Encode; use
#!/usr/bin/perl -w
use strict;
use warnings;
use 5.010;
use DBI;
use Encode;
use IO::File;
use JSON;
use utf8;
BEGIN {
binmode STDERR, ':utf8';
binmode STDIN, ':utf8';
binmode STDOUT, ':utf8';
}
my $time = localtime();
my $file = '/opt/db-servers/db.txt';
open my $info, $file or die "Could not open $file: $!";
while( my $hostname = <$info>) {
chomp( $hostname );
my $xtrabk_check = `ssh $hostname ps -ef |grep mysql | grep wsrep_sst_xtrabackup-v2`;
my $role_check = `ssh $hostname ps -ef |grep mysql | grep donor`;
my $error_log = `ssh $hostname ps -ef |grep mysql`;
if ( $xtrabk_check ne "" ){
if ( $role_check ne "" ){
my $cmd ="curl -vs -o /dev/null -X POST --data-urlencode 'payload={\"channel\": \"#db-wsrep-status-log\", \"username\": \"db-wsrep-status-log\", \"text\": \"$time: $hostname: --role Donor \n```$error_log```\", \"icon_emoji\": \":scorpion:\"}' 2>&1 /dev/null https://hooks.slack.com/services/GVadasdd/B6LSMF5GV/BIApnzoIldfdsrw343wf";
system($cmd);
}
else {
my $cmd ="curl -vs -o /dev/null -X POST --data-urlencode 'payload={\"channel\": \"#db-wsrep-status-log\", \"username\": \"db-wsrep-status-log\", \"text\": \"$time: $hostname: State transfer in progress, setting sleep higher mysqld \n```$error_log```\", \"icon_emoji\": \":scorpion:\"}' 2>&1 https://hooks.slack.com/services/GVadasdd/B6LSMF5GV/BIApnzoIldfdsrw343wf";
system($cmd);
}
}
}
close $info;
我如何才能做到这一点?顺便说一句,松弛URL已被更改,因此存在安全问题。到目前为止,确定是否可以通过ssh连接到服务器的最可靠方法是实际尝试通过ssh连接到服务器。只需尝试连接,如果失败,请报告失败并中止任何进一步的尝试:
use Try::Tiny;
# Declaring them here so they don't disappear at the end of the try block
my ($xtrabk_check, $role_check, $error_log);
try {
$xtrabk_check = `ssh $hostname ps -ef |grep mysql | grep wsrep_sst_xtrabackup-v2`;
$role_check = `ssh $hostname ps -ef |grep mysql | grep donor`;
$error_log = `ssh $hostname ps -ef |grep mysql`;
} catch {
die "Failed to connect to ssh: $_";
}
不要直接运行
ssh
,而是使用支持ssh的任何Perl模块(例如,)。这将允许您连接到远程主机,并在单个连接上运行所需数量的命令,它将检测任何连接错误并适当地报告
您还可以使用来并行化操作
use Try::Tiny;
# Declaring them here so they don't disappear at the end of the try block
my ($xtrabk_check, $role_check, $error_log);
try {
$xtrabk_check = `ssh $hostname ps -ef |grep mysql | grep wsrep_sst_xtrabackup-v2`;
$role_check = `ssh $hostname ps -ef |grep mysql | grep donor`;
$error_log = `ssh $hostname ps -ef |grep mysql`;
} catch {
die "Failed to connect to ssh: $_";
}