Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Expect to enter a password for a Perl script?

Tags:

perl

expect

I wish to automatically enter a password while running an install script. I have invoked the install script using the backticks in Perl. Now my issue is how do I enter that password using expect or something else?

my $op = `install.sh -f my_conf -p my_ip -s my_server`;

When the above is executed, a password line is printed:

Enter password for the packagekey: 

In the above line I wish to enter the password.

like image 678
gagneet Avatar asked Sep 02 '09 09:09

gagneet


3 Answers

use Expect.pm.

This module is especially tailored for programatic control of applications which require user feedback

#!/usr/bin/perl

use strict;
use warnings;

use Expect;

my $expect      = Expect->new;
my $command     = 'install.sh';
my @parameters  = qw(-f my_conf -p my_ip -s my_server);
my $timeout     = 200;
my $password    = "W31C0m3";

$expect->raw_pty(1);  
$expect->spawn($command, @parameters)
    or die "Cannot spawn $command: $!\n";

$expect->expect($timeout,
                [   qr/Enter password for the packagekey:/i, #/
                    sub {
                        my $self = shift;
                        $self->send("$password\n");
                        exp_continue;
                    }
                ]);
like image 164
dsm Avatar answered Oct 23 '22 05:10

dsm


If the program reads the password from standard input, you can just pipe it in:

`echo password | myscript.sh (...)`

If not, Expect or PTYs.

like image 3
JB. Avatar answered Oct 23 '22 06:10

JB.


You can save the password in a file and while running the install script, read the password from the file.

like image 1
PJ. Avatar answered Oct 23 '22 05:10

PJ.