in reply to Net::SSH2 to capture multiple commands on remote system
Hello bellis,
Recently I had similar request like yours and I end up creating several different solutions. One of them is provided bellow. I am using Net::OpenSSH as the module for my purposes.
On the example given bellow you are also able to execute sudo commands, something that I found difficult at the beginning but mandatory for my task. I have also created more complicated solutions with the same module reading from several servers sequentially, if you have similar problem just let me know and I will post working samples of code for you to modify based on your criteria.
#!/usr/bin/perl use Expect; use strict; use warnings; use Data::Dumper; use Net::OpenSSH; select STDOUT; $| = 1; select STDERR; $| = 1; my $password = "Your Password Here"; my $port = 22; # default 22 if you have changed modify it my $timeout = 20; my $debug = 0; my $ssh = Net::OpenSSH->new( 'username@127.0.0.1' , password => $passw +ord , port => $port ); my ($pty, $pid) = $ssh->open2pty("sudo cat /etc/shells") # After a successful sudo operation, it doesn't request the password # again until some time after, handling this undeterministic behavior # is a pain in the ass, so we just clear any cached credentials # calling "sudo -k" first as follows: =comment my ($pty, $pid) = $ssh->open2pty("sudo -k; sudo ntpdate ntp.ubuntu +.com") or die "open2pty failed: " . $ssh->error . "\n"; =cut my $expect = Expect->init($pty); $expect->raw_pty(1); $debug and $expect->log_user(1); $debug and print "waiting for password prompt\n"; $expect->expect($timeout, ':') or die "expect failed\n"; $debug and print "prompt seen\n"; $expect->send("$password\n"); $debug and print "password sent\n"; $expect->expect($timeout, "\n") or die "bad password\n"; $debug and print "password ok\n"; my @array = (); my @final = (); while(<$pty>) { push (@array,$_); print "This is the return: $. $_" } foreach my $line (@array) { chomp($line); $_ = "Modify $line"; #$line =~ s/;//; push(@final,$_); } print Dumper(\@final); __END__ This is the return: 1 # /etc/shells: valid login shells This is the return: 2 /bin/sh This is the return: 3 /bin/dash This is the return: 4 /bin/bash This is the return: 5 /bin/rbash $VAR1 = [ ', 'Modify # /etc/shells: valid login shells ', 'Modify /bin/sh ', 'Modify /bin/dash ', 'Modify /bin/bash ' 'Modify /bin/rbash ];
Other modules to take in consideration are Net::SSH::Perl and Net::Telnet. From my point of view they are a bit more complicated but in case you need some sample of code just let me know I have some samples that you can modify.
Hope I did not confused you more than I simplified the solution to your problem.
|
|---|