Bash/Expect Script for SSH

前端 未结 4 491
旧时难觅i
旧时难觅i 2021-01-05 06:36

I am new to Expect and scripting in general. I am trying to make a few scripts to make my life a bit easier when pulling network device configurations. I managed to create a

4条回答
  •  旧时难觅i
    2021-01-05 07:13

    This is a Perl version for this issue:

    Install instruction:

    cpan Expect
    

    This script works perfectly for my needs.

    Parameter 1: Connection string (example: admin@10.34.123.10)
    Parameter 2: Clear text password
    Parameter 3: Command to execute

    #!/usr/bin/perl
    use strict;
    
    use Expect;
    
    my $timeout = 1;
    
    my $command = "ssh " . $ARGV[0] . " " . $ARGV[2];
    
    #print " => $command\n";
    
    my $exp = Expect->spawn($command) or die "Cannot spawn $command: $!\n";
    $exp->raw_pty(1);
    
    LOGIN:
    $exp->expect($timeout,
            [ 'ogin: $' => sub {
                         $exp->send("luser\n");
                         exp_continue;
                    }
            ],
            [ 'yes\/no\)\?\s*$' => sub {
                        $exp->send("yes\n");
                        goto LOGIN;
                    }
            ],
            [ 'assword:\s*$' => sub {
                        $exp->send($ARGV[1]."\n");
                        #print "password send: ", $ARGV[1];
                        exp_continue;
                    }
            ],
            '-re', qr'[#>:] $'
    );
    $exp->soft_close();
    

提交回复
热议问题