From 7d2404688f803123733f43689ebbcb9ab393b055 Mon Sep 17 00:00:00 2001 From: Dobrica Pavlinusic Date: Thu, 17 Sep 2015 19:17:28 +0200 Subject: [PATCH] spoon-feed slow switch, save output in log git repo --- dell-switch.pl | 55 ++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 42 insertions(+), 13 deletions(-) diff --git a/dell-switch.pl b/dell-switch.pl index f23546a..5b9109c 100755 --- a/dell-switch.pl +++ b/dell-switch.pl @@ -5,11 +5,11 @@ use autodie; use Net::OpenSSH; use Data::Dump qw(dump); -use List::Util qw(first); -use Time::HiRes; +use Time::HiRes qw(sleep); our $login; our $passwd; +our $debug = $ENV{DEBUG} || 0; require 'config.pl'; @@ -25,39 +25,68 @@ my ($pty ,$pid) = $ssh->open2pty(); my $buff; +sub send_pty { + my $string = shift; + sleep 0.1; # we really need to wait for slow PowerConnect 5324 + foreach (split //, $string) { + print STDERR "[$_]" if $debug; + syswrite $pty, $_; +# $pty->flush; + sysread $pty, my $echo, 1; + print STDERR $echo; + $buff .= $echo; + } +} + +mkdir 'log' unless -d 'log'; + +chdir 'log'; + +sub save_log { + my ($ip, $hostname, $command, $buff) = @_; + + my $file = "${ip}_${hostname}_${command}.log"; + open my $log, '>', $file; + $buff =~ s/\r//gs; # strip CR, leave LF only + print $log $buff; + if ( -e '.git' ) { + system 'git', 'add', $file; + system 'git', 'commit', '-m', "$ip $hostname", $file; + } +} + +my $command; + while(1) { my $data; my $read = sysread($pty, $data, 1); print STDERR $data; $buff .= $data; if ( $buff =~ m/User Name:/ ) { - print $pty "$login\n"; + send_pty "$login\n"; $buff = ''; } elsif ( $buff =~ m/Password:/ ) { - print $pty "$passwd\n"; + send_pty "$passwd\n"; $buff = ''; } elsif ( $buff =~ m/([\w\-]+)#$/ ) { my $hostname = $1; if ( $buff ) { - mkdir 'log' unless -d 'log'; - open my $log, '>>', "log/$ip-$hostname.log"; - print $log $buff; + save_log $ip, $hostname, $command, $buff; $buff = ''; } - if ( my $command = shift @commands ) { - $command .= "\n" unless $command =~ m/\n$/; - warn ">> $command\n"; - print $pty "$command"; + if ( $command = shift @commands ) { + $command =~ s/[\n\r]+$//; + send_pty "$command\n"; $buff = ''; } else { - print $pty "exit\n"; + send_pty "exit\n"; close($pty); last; } } elsif ( $buff =~ m/% Unrecognized command/ ) { exit 1; } elsif ( $buff =~ s{More: , Quit: q, One line: }{} ) { - print $pty " "; + send_pty " "; } elsif ( $buff =~ s{\e\[0m\r\s+\r}{} ) { } } -- 2.20.1