Advertisement
Guest User

Untitled

a guest
Mar 1st, 2019
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. use strict;
  2. use warnings;
  3. use Net::SSH2;
  4.  
  5. my %args = (hostname => 'myhost', password => 'XXX', username => 'root');
  6. my $ssh = Net::SSH2->new;
  7.  
  8. sub get_ssh_output {
  9. my ($chan) = @_;
  10.  
  11. my ($stdout, $stderr) = ('', '');
  12. while (!$chan->eof) {
  13. if (my ($o, $e) = $chan->read2) {
  14. $stdout .= $o;
  15. $stderr .= $e;
  16. }
  17. }
  18. chomp($stdout, $stderr);
  19. print "Command's stdout:\n$stdout\n" if length($stdout);
  20. print "Command's stderr:\n$stderr\n" if length($stderr);
  21. return $stdout, $stderr if wantarray;
  22. }
  23.  
  24. sub run_cmd {
  25. my ($cmd) = @_;
  26.  
  27. my $chan = $ssh->channel();
  28. $chan->exec($cmd);
  29. print "Command executed: $cmd\n";
  30. get_ssh_output($chan);
  31. $chan->send_eof;
  32. my $ret = $chan->exit_status();
  33. $chan->close();
  34. return $ret;
  35. }
  36.  
  37. sub run_ssh_cmd {
  38. my ($cmd) = @_;
  39.  
  40. my $ssh = Net::SSH2->new;
  41. $ssh->connect($args{hostname}) or die "failed to connect";
  42. $ssh->auth(username => $args{username}, password => $args{password});
  43. die "authentication failed" unless $ssh->auth_ok;
  44. my $chan = $ssh->channel();
  45. $chan->exec($cmd);
  46. get_ssh_output($chan);
  47. $chan->send_eof;
  48. my $ret = $chan->exit_status();
  49. print "Command executed: $cmd, ret=$ret\n";
  50. $chan->close();
  51. return $ret;
  52. }
  53.  
  54. # Retry 5 times, in case of the guest is not running yet
  55. my $counter = 5;
  56. while ($counter > 0) {
  57. if ($ssh->connect($args{hostname})) {
  58.  
  59. if ($args{password}) {
  60. $ssh->auth(username => $args{username}, password => $args{password});
  61. }
  62. else {
  63. # this relies on agent to be set up correctly
  64. $ssh->auth_agent($args{username});
  65. }
  66. print "Connection to $args{username}\@$args{hostname} established\n" if $ssh->auth_ok;
  67. last;
  68. }
  69. else {
  70. print "Could not connect to $args{username}\@$args{hostname}, Retry\n";
  71. sleep(10);
  72. $counter--;
  73. next;
  74. }
  75. }
  76. die "Error connecting to <$args{username}\@$args{hostname}>: $@" unless $ssh->auth_ok;
  77.  
  78. for (1 .. 100) {
  79. print "$_: ";
  80. #die "run_cmd failed" if run_cmd("! virsh dominfo openQA-SUT-4 | grep -w 'shut off'");
  81. die "run_cmd failed" if run_ssh_cmd("! virsh dominfo openQA-SUT-4 | grep -w 'shut off'");
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement