Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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'");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement