Created
February 25, 2019 21:27
-
-
Save okurz/1e82cdecf6e5c478119a58964117e119 to your computer and use it in GitHub Desktop.
test_ssh.pl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use strict; | |
use warnings; | |
use Net::SSH2; | |
my %args = (hostname => 'myhost', password => 'XXX', username => 'root'); | |
my $ssh = Net::SSH2->new; | |
sub get_ssh_output { | |
my ($chan) = @_; | |
my ($stdout, $stderr) = ('', ''); | |
while (!$chan->eof) { | |
if (my ($o, $e) = $chan->read2) { | |
$stdout .= $o; | |
$stderr .= $e; | |
} | |
} | |
chomp($stdout, $stderr); | |
print "Command's stdout:\n$stdout\n" if length($stdout); | |
print "Command's stderr:\n$stderr\n" if length($stderr); | |
return $stdout, $stderr if wantarray; | |
} | |
sub run_cmd { | |
my ($cmd) = @_; | |
my $chan = $ssh->channel(); | |
$chan->exec($cmd); | |
print "Command executed: $cmd\n"; | |
get_ssh_output($chan); | |
$chan->send_eof; | |
my $ret = $chan->exit_status(); | |
$chan->close(); | |
return $ret; | |
} | |
sub run_ssh_cmd { | |
my ($cmd) = @_; | |
my $ssh = Net::SSH2->new; | |
$ssh->connect($args{hostname}) or die "failed to connect"; | |
$ssh->auth(username => $args{username}, password => $args{password}); | |
die "authentication failed" unless $ssh->auth_ok; | |
my $chan = $ssh->channel(); | |
$chan->exec($cmd); | |
get_ssh_output($chan); | |
$chan->send_eof; | |
my $ret = $chan->exit_status(); | |
print "Command executed: $cmd, ret=$ret\n"; | |
$chan->close(); | |
return $ret; | |
} | |
# Retry 5 times, in case of the guest is not running yet | |
my $counter = 5; | |
while ($counter > 0) { | |
if ($ssh->connect($args{hostname})) { | |
if ($args{password}) { | |
$ssh->auth(username => $args{username}, password => $args{password}); | |
} | |
else { | |
# this relies on agent to be set up correctly | |
$ssh->auth_agent($args{username}); | |
} | |
print "Connection to $args{username}\@$args{hostname} established\n" if $ssh->auth_ok; | |
last; | |
} | |
else { | |
print "Could not connect to $args{username}\@$args{hostname}, Retry\n"; | |
sleep(10); | |
$counter--; | |
next; | |
} | |
} | |
die "Error connecting to <$args{username}\@$args{hostname}>: $@" unless $ssh->auth_ok; | |
for (1 .. 100) { | |
print "$_: "; | |
#die "run_cmd failed" if run_cmd("! virsh dominfo openQA-SUT-4 | grep -w 'shut off'"); | |
die "run_cmd failed" if run_ssh_cmd("! virsh dominfo openQA-SUT-4 | grep -w 'shut off'"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment