Skip to content
Advertisement

Facing issues writing code with perl expect

I want to run a command which will connect to a remote host and perform some actions, while I try to run the command below actions are required.

The authenticity of host 'test.example.com' can't be established.
RSA key fingerprint is 45:57:9e:d6:6f:b5:cc:c6:00:3f:90:ec:a1:9d:4e:5f.
Are you sure you want to continue connecting (yes/no)?
Please type 'yes' or 'no': 

also it asks for a password as below

tes@test.example.com's password:

I have written a perl script as below:

sub user_expect()
{
    print "==== Now executing the following command:n";
    print "$cmdn";
    $exp = new Expect();
    $exp->raw_pty(1);
    $exp->log_file("output2_user", "w");
    $exp->debug($debug);
    $exp->spawn("$cmd");
    $exp->expect($timeout,'-re', '?s$'); # Authenticity question (yes/no)
    $exp->send("yesn");
    $exp->expect($timeout,'-re', ':s$'); # In case on console am expected to type yes/no - Please type 'yes' or 'no': 
    $exp->send("yesn");
    $exp->expect($timeout,'-re', 'word:$'); # enter password
    $exp->send("xyzn");
    $exp->expect(500,'-re', 'mailbox deleted successfully.$');
    $exp->hard_close();
    return 1;
}

I needed a code which can answer the questions asked on console i.e. as below and also the password console

The authenticity of host 'test.example.com' can't be established.
RSA key fingerprint is 45:57:9e:d6:6f:b5:cc:c6:00:3f:90:ec:a1:9d:4e:5f.
Are you sure you want to continue connecting (yes/no)?
Please type 'yes' or 'no': 

I am not sure on the mistake I have done regarding the script, can someone please help ?

Problem is – I think the “yes” that needs to be typed for below query is not taken because of which the query “Please type ‘yes’ or ‘no’: ” is shown on console. Then my script stops there and does not proceed with password prompt.

Are you sure you want to continue connecting (yes/no)?

Advertisement

Answer

I changed the code as below, it was successful:

sub rehostuser_expect() {
    $expect= Expect->new;
    $expect->raw_pty(1);
    $expect->spawn($cmd)
    or die "Cannot spawn $cmd: $!n";

    $expect->expect($timeout,
            [   qr/.*?/i, #/
            sub {
                    my $self = shift;
                    $self->send("yesrn");
                    exp_continue;
                    }
            ]);

    $expect->expect($timeout,
            [   qr/password:/i, #/
            sub {
                    my $self = shift;
                    $self->send("$passwordn");
                    exp_continue;
            }
    ]);
    $expect->hard_close();
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement