don't save files without command (prompt only)
[dell-switch] / dell-switch.pl
1 #!/usr/bin/perl
2 use warnings;
3 use strict;
4 use autodie;
5
6 use Net::OpenSSH;
7 use Data::Dump qw(dump);
8 use Time::HiRes qw(sleep);
9
10 our $login;
11 our $passwd;
12 our $debug = $ENV{DEBUG} || 0;
13
14 require 'config.pl';
15
16 #$Net::OpenSSH::debug = ~0;
17
18 my $ip = shift @ARGV || '10.20.0.2';
19 my @commands = @ARGV;
20 @commands = <DATA> unless @commands;
21
22 warn "## $ip\n";
23 my $ssh = Net::OpenSSH->new('auto@'.$ip);
24 my ($pty ,$pid) = $ssh->open2pty();
25
26 my $buff;
27
28 sub send_pty {
29         my $string = shift;
30         sleep 0.1; # we really need to wait for slow PowerConnect 5324
31         foreach (split //, $string) {
32                 print STDERR "[$_]" if $debug;
33                 syswrite $pty, $_;
34 #               $pty->flush;
35                 sysread $pty, my $echo, 1;
36                 print STDERR $echo;
37                 $buff .= $echo;
38         }
39 }
40
41 mkdir 'log' unless -d 'log';
42
43 chdir 'log';
44
45 sub save_log {
46         my ($ip, $hostname, $command, $buff) = @_;
47
48         return unless $command;
49         
50         my $file = "${ip}_${hostname}_${command}.log";
51         open my $log, '>', $file;
52         $buff =~ s/\r//gs; # strip CR, leave LF only
53         print $log $buff;
54         if ( -e '.git' ) {
55                 system 'git', 'add', $file;
56                 system 'git', 'commit', '-m', "$ip $hostname", $file;
57         }
58 }
59
60 my $command;
61
62 while(1) {
63         my $data;
64         my $read = sysread($pty, $data, 1);
65         print STDERR $data;
66         $buff .= $data;
67         if ( $buff =~ m/User Name:/ ) {
68                 send_pty "$login\n";
69                 $buff = '';
70         } elsif ( $buff =~ m/Password:/ ) {
71                 send_pty "$passwd\n";
72                 $buff = '';
73         } elsif ( $buff =~ m/([\w\-]+)#$/ ) {
74                 my $hostname = $1;
75                 if ( $buff ) {
76                         save_log $ip, $hostname, $command, $buff;
77                         $buff = '';
78                 }
79                 if ( $command = shift @commands ) {
80                         $command =~ s/[\n\r]+$//;
81                         send_pty "$command\n";
82                         $buff = '';
83                 } else  {
84                         send_pty "exit\n";
85                         close($pty);
86                         last;
87                 }
88         } elsif ( $buff =~ m/% Unrecognized command/ ) {
89                 exit 1;
90         } elsif ( $buff =~ s{More: <space>,  Quit: q, One line: <return> }{} ) {
91                 send_pty " ";
92         } elsif ( $buff =~ s{\e\[0m\r\s+\r}{} ) {
93         }
94 }
95
96 __DATA__
97 show arp
98 show vlan
99 show running-config
100 show bridge address-table