【问题标题】:How can I use Expect to enter a password for a Perl script?如何使用 Expect 为 Perl 脚本输入密码?
【发布时间】:2010-11-24 21:40:38
【问题描述】:

我希望在运行安装脚本时自动输入密码。我已经使用 Perl 中的反引号调用了安装脚本。现在我的问题是如何使用expect 或其他方式输入该密码?

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

执行上述操作时,会打印密码行:

Enter password for the packagekey: 

在上面一行我想输入密码。

【问题讨论】:

    标签: perl expect


    【解决方案1】:

    使用Expect.pm

    此模块专为需要用户反馈的应用程序的编程控制而量身定制

    #!/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;
                        }
                    ]);
    

    【讨论】:

      【解决方案2】:

      您可以将密码保存在文件中,并在运行安装脚本时从文件中读取密码。

      【讨论】:

        【解决方案3】:

        如果程序从标准输入读取密码,你可以直接输入:

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

        如果没有,Expect 或 PTY。

        【讨论】:

        • 它不起作用,因为如果在您的密码中使用任何特殊字符。示例错误消息 在字符串中,@ug 现在必须在 gsx.pl 第 5 行写为 \@ug,靠近“echo RRRRR@ug” 全局符号“@ug”需要在 gsx.pl 第 5 行显示包名
        • 如果您的密码中有特殊字符,您可以找到在上下文中转义它们的正确方法。它存在。
        猜你喜欢
        • 2017-01-30
        • 1970-01-01
        • 1970-01-01
        • 2018-07-07
        • 2011-06-14
        • 1970-01-01
        • 2012-08-25
        相关资源
        最近更新 更多